/** * Returns a byte array representation of the file given by the URL. The file is downloaded and * optionally stored on the filesystem. * * @param u URL to retrieve. * @param @param saveOnDisk If true, store the file on the filesystem. * @param f If saveOnDisk is true, then store the contents of the file represented by u in the * associated File. f needs to be opened before calling this function. * @return The byte array * @throws IOException */ protected static byte[] downloadAndSendBinary(String u, boolean saveOnDisk, File f) throws IOException { URL url = new URL(u); // The URL may contain user authentication information Authenticator.setDefault(new HTTPResourceAuthenticator()); HTTPResourceAuthenticator.addURL(url); LOGGER.debug("Retrieving " + url.toString()); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); URLConnection conn = url.openConnection(); // GameTrailers blocks user-agents that identify themselves as "Java" conn.setRequestProperty( "User-agent", PropertiesUtil.getProjectProperties().get("project.name") + " " + PMS.getVersion()); InputStream in = conn.getInputStream(); FileOutputStream fOUT = null; if (saveOnDisk && f != null) { // fileName = convertURLToFileName(fileName); fOUT = new FileOutputStream(f); } byte[] buf = new byte[4096]; int n; while ((n = in.read(buf)) > -1) { bytes.write(buf, 0, n); if (fOUT != null) { fOUT.write(buf, 0, n); } } in.close(); if (fOUT != null) { fOUT.close(); } return bytes.toByteArray(); }
public JComponent build() { FormLayout layout = new FormLayout( "0:grow, pref, 0:grow", "pref, 3dlu, pref, 3dlu, pref, 12dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, p, 3dlu, p"); PanelBuilder builder = new PanelBuilder(layout); builder.setDefaultDialogBorder(); builder.setOpaque(true); CellConstraints cc = new CellConstraints(); String projectName = PropertiesUtil.getProjectProperties().get("project.name"); final LinkMouseListener pms3Link = new LinkMouseListener( projectName + " " + PMS.getVersion(), "http://www.ps3mediaserver.org/"); JLabel lPms3Link = builder.addLabel(pms3Link.getLabel(), cc.xy(2, 1, "center, fill")); lPms3Link.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); lPms3Link.addMouseListener(pms3Link); // Create a build name from the available git properties String commitId = PropertiesUtil.getProjectProperties().get("git.commit.id"); String commitTime = PropertiesUtil.getProjectProperties().get("git.commit.time"); String shortCommitId = commitId.substring(0, 9); String commitUrl = "https://github.com/ps3mediaserver/ps3mediaserver/commit/" + commitId; String buildLabel = Messages.getString("LinksTab.6") + " " + shortCommitId + " (" + commitTime + ")"; final LinkMouseListener commitLink = new LinkMouseListener(buildLabel, commitUrl); JLabel lCommitLink = builder.addLabel(commitLink.getLabel(), cc.xy(2, 3, "center, fill")); lCommitLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); lCommitLink.addMouseListener(commitLink); imagePanel = buildImagePanel(); builder.add(imagePanel, cc.xy(2, 5, "center, fill")); builder.addLabel(Messages.getString("LinksTab.5"), cc.xy(2, 7, "center, fill")); final LinkMouseListener ffmpegLink = new LinkMouseListener("FFmpeg", "http://ffmpeg.mplayerhq.hu"); JLabel lFfmpegLink = builder.addLabel(ffmpegLink.getLabel(), cc.xy(2, 9, "center, fill")); lFfmpegLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); lFfmpegLink.addMouseListener(ffmpegLink); final LinkMouseListener mplayerLink = new LinkMouseListener("MPlayer", "http://www.mplayerhq.hu"); JLabel lMplayerLink = builder.addLabel(mplayerLink.getLabel(), cc.xy(2, 11, "center, fill")); lMplayerLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); lMplayerLink.addMouseListener(mplayerLink); final LinkMouseListener vlcLink = new LinkMouseListener("VLC media player", "http://www.videolan.org/vlc/"); JLabel lVlcLink = builder.addLabel(vlcLink.getLabel(), cc.xy(2, 13, "center, fill")); lVlcLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); lVlcLink.addMouseListener(vlcLink); final LinkMouseListener mediaInfoLink = new LinkMouseListener("MediaInfo", "http://mediainfo.sourceforge.net/en"); JLabel lMediaInfoLink = builder.addLabel(mediaInfoLink.getLabel(), cc.xy(2, 15, "center, fill")); lMediaInfoLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); lMediaInfoLink.addMouseListener(mediaInfoLink); JScrollPane scrollPane = new JScrollPane(builder.getPanel()); scrollPane.setBorder(BorderFactory.createEmptyBorder()); return scrollPane; }
public void init(boolean force) { dbCount = -1; String version = null; Connection conn = null; ResultSet rs = null; Statement stmt = null; try { conn = getConnection(); } catch (SQLException se) { final File dbFile = new File(dbDir + File.separator + dbName + ".data.db"); final File dbDirectory = new File(dbDir); if (dbFile.exists() || (se.getErrorCode() == 90048)) { // Cache is corrupt or wrong version, so delete it FileUtils.deleteQuietly(dbDirectory); if (!dbDirectory.exists()) { LOGGER.debug( "The cache has been deleted because it was corrupt or had the wrong version"); } else { if (!PMS.isHeadless()) { JOptionPane.showMessageDialog( (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())), String.format(Messages.getString("DLNAMediaDatabase.5"), dbDir), Messages.getString("Dialog.Error"), JOptionPane.ERROR_MESSAGE); } LOGGER.debug( "Damaged cache can't be deleted. Stop the program and delete the folder \"" + dbDir + "\" manually"); configuration.setUseCache(false); return; } } else { LOGGER.debug("Cache connection error: " + se.getMessage()); configuration.setUseCache(false); return; } } try { conn = getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT count(*) FROM FILES"); if (rs.next()) { dbCount = rs.getInt(1); } rs.close(); stmt.close(); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT VALUE FROM METADATA WHERE KEY = 'VERSION'"); if (rs.next()) { version = rs.getString(1); } } catch (SQLException se) { if (se.getErrorCode() != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in // following step LOGGER.error(null, se); } } finally { close(rs); close(stmt); close(conn); } boolean force_reinit = !PMS.getVersion().equals(version); // here we can force a deletion for a specific version if (force || dbCount == -1 || force_reinit) { LOGGER.debug("Database will be (re)initialized"); try { conn = getConnection(); executeUpdate(conn, "DROP TABLE FILES"); executeUpdate(conn, "DROP TABLE METADATA"); executeUpdate(conn, "DROP TABLE REGEXP_RULES"); executeUpdate(conn, "DROP TABLE AUDIOTRACKS"); executeUpdate(conn, "DROP TABLE SUBTRACKS"); } catch (SQLException se) { if (se.getErrorCode() != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in // following step LOGGER.error(null, se); } } try { StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE FILES ("); sb.append(" ID INT AUTO_INCREMENT"); sb.append(", FILENAME VARCHAR2(1024) NOT NULL"); sb.append(", MODIFIED TIMESTAMP NOT NULL"); sb.append(", TYPE INT"); sb.append(", DURATION DOUBLE"); sb.append(", BITRATE INT"); sb.append(", WIDTH INT"); sb.append(", HEIGHT INT"); sb.append(", SIZE NUMERIC"); sb.append(", CODECV VARCHAR2(").append(SIZE_CODECV).append(")"); sb.append(", FRAMERATE VARCHAR2(").append(SIZE_FRAMERATE).append(")"); sb.append(", ASPECT VARCHAR2(").append(SIZE_ASPECT).append(")"); sb.append(", ASPECTRATIOCONTAINER VARCHAR2(") .append(SIZE_ASPECTRATIO_CONTAINER) .append(")"); sb.append(", ASPECTRATIOVIDEOTRACK VARCHAR2(") .append(SIZE_ASPECTRATIO_VIDEOTRACK) .append(")"); sb.append(", REFRAMES TINYINT"); sb.append(", AVCLEVEL VARCHAR2(").append(SIZE_AVC_LEVEL).append(")"); sb.append(", BITSPERPIXEL INT"); sb.append(", THUMB BINARY"); sb.append(", CONTAINER VARCHAR2(").append(SIZE_CONTAINER).append(")"); sb.append(", MODEL VARCHAR2(").append(SIZE_MODEL).append(")"); sb.append(", EXPOSURE INT"); sb.append(", ORIENTATION INT"); sb.append(", ISO INT"); sb.append(", MUXINGMODE VARCHAR2(").append(SIZE_MUXINGMODE).append(")"); sb.append(", FRAMERATEMODE VARCHAR2(").append(SIZE_FRAMERATE_MODE).append(")"); sb.append(", constraint PK1 primary key (FILENAME, MODIFIED, ID))"); executeUpdate(conn, sb.toString()); sb = new StringBuilder(); sb.append("CREATE TABLE AUDIOTRACKS ("); sb.append(" FILEID INT NOT NULL"); sb.append(", ID INT NOT NULL"); sb.append(", LANG VARCHAR2(").append(SIZE_LANG).append(")"); sb.append(", FLAVOR VARCHAR2(").append(SIZE_FLAVOR).append(")"); sb.append(", NRAUDIOCHANNELS NUMERIC"); sb.append(", SAMPLEFREQ VARCHAR2(").append(SIZE_SAMPLEFREQ).append(")"); sb.append(", CODECA VARCHAR2(").append(SIZE_CODECA).append(")"); sb.append(", BITSPERSAMPLE INT"); sb.append(", ALBUM VARCHAR2(").append(SIZE_ALBUM).append(")"); sb.append(", ARTIST VARCHAR2(").append(SIZE_ARTIST).append(")"); sb.append(", SONGNAME VARCHAR2(").append(SIZE_SONGNAME).append(")"); sb.append(", GENRE VARCHAR2(").append(SIZE_GENRE).append(")"); sb.append(", YEAR INT"); sb.append(", TRACK INT"); sb.append(", DELAY INT"); sb.append(", MUXINGMODE VARCHAR2(").append(SIZE_MUXINGMODE).append(")"); sb.append(", BITRATE INT"); sb.append(", constraint PKAUDIO primary key (FILEID, ID))"); executeUpdate(conn, sb.toString()); sb = new StringBuilder(); sb.append("CREATE TABLE SUBTRACKS ("); sb.append(" FILEID INT NOT NULL"); sb.append(", ID INT NOT NULL"); sb.append(", LANG VARCHAR2(").append(SIZE_LANG).append(")"); sb.append(", FLAVOR VARCHAR2(").append(SIZE_FLAVOR).append(")"); sb.append(", TYPE INT"); sb.append(", constraint PKSUB primary key (FILEID, ID))"); executeUpdate(conn, sb.toString()); executeUpdate( conn, "CREATE TABLE METADATA (KEY VARCHAR2(255) NOT NULL, VALUE VARCHAR2(255) NOT NULL)"); executeUpdate(conn, "INSERT INTO METADATA VALUES ('VERSION', '" + PMS.getVersion() + "')"); executeUpdate(conn, "CREATE INDEX IDXARTIST on AUDIOTRACKS (ARTIST asc);"); executeUpdate(conn, "CREATE INDEX IDXALBUM on AUDIOTRACKS (ALBUM asc);"); executeUpdate(conn, "CREATE INDEX IDXGENRE on AUDIOTRACKS (GENRE asc);"); executeUpdate(conn, "CREATE INDEX IDXYEAR on AUDIOTRACKS (YEAR asc);"); executeUpdate( conn, "CREATE TABLE REGEXP_RULES ( ID VARCHAR2(255) PRIMARY KEY, RULE VARCHAR2(255), ORDR NUMERIC);"); executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '###', '(?i)^\\W.+', 0 );"); executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '0-9', '(?i)^\\d.+', 1 );"); // Retrieve the alphabet property value and split it String[] chars = Messages.getString("DLNAMediaDatabase.1").split(","); for (int i = 0; i < chars.length; i++) { // Create regexp rules for characters with a sort order based on the property value executeUpdate( conn, "INSERT INTO REGEXP_RULES VALUES ( '" + chars[i] + "', '(?i)^" + chars[i] + ".+', " + (i + 2) + " );"); } LOGGER.debug("Database initialized"); } catch (SQLException se) { LOGGER.info("Error in table creation: " + se.getMessage()); } finally { close(conn); } } else { LOGGER.debug("Database file count: " + dbCount); LOGGER.debug("Database version: " + version); } }
public void init() { try { db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); UMSHeaders = new UpnpHeaders(); UMSHeaders.add( UpnpHeader.Type.USER_AGENT.getHttpName(), "UMS/" + PMS.getVersion() + " " + new ServerClientTokens()); DefaultUpnpServiceConfiguration sc = new DefaultUpnpServiceConfiguration() { @Override public UpnpHeaders getDescriptorRetrievalHeaders(RemoteDeviceIdentity identity) { return UMSHeaders; } }; RegistryListener rl = new DefaultRegistryListener() { @Override public void remoteDeviceAdded(Registry registry, RemoteDevice d) { super.remoteDeviceAdded(registry, d); if (isBlocked(getUUID(d)) || !addRenderer(d)) { LOGGER.debug("Ignoring device: {} {}", d.getType().getType(), d.toString()); } // This may be unnecessary, but we might as well be thorough if (d.hasEmbeddedDevices()) { for (Device e : d.getEmbeddedDevices()) { if (isBlocked(getUUID(e)) || !addRenderer(e)) { LOGGER.debug("Ignoring embedded device: {} {}", e.getType(), e.toString()); } } } } @Override public void remoteDeviceRemoved(Registry registry, RemoteDevice d) { super.remoteDeviceRemoved(registry, d); String uuid = getUUID(d); if (rendererMap.containsKey(uuid)) { rendererMap.mark(uuid, ACTIVE, false); rendererRemoved(d); } } @Override public void remoteDeviceUpdated(Registry registry, RemoteDevice d) { super.remoteDeviceUpdated(registry, d); rendererUpdated(d); } }; upnpService = new UpnpServiceImpl(sc, rl); // find all media renderers on the network for (DeviceType t : mediaRendererTypes) { upnpService.getControlPoint().search(new DeviceTypeHeader(t)); } LOGGER.debug("UPNP Services are online, listening for media renderers"); } catch (Exception ex) { LOGGER.debug("UPNP startup Error", ex); } }