List of usage examples for java.net URL openStream
public final InputStream openStream() throws java.io.IOException
From source file:at.becast.youploader.database.SQLite.java
public static void updatePlaylist(Item item) throws SQLException, IOException { PreparedStatement prest = null; String sql = "UPDATE `playlists` SET `name`=?,`image`=? WHERE `playlistid`=?"; prest = c.prepareStatement(sql);// w w w . ja va 2 s .com prest.setString(1, item.snippet.title); URL url = new URL(item.snippet.thumbnails.default__.url); InputStream is = null; is = url.openStream(); byte[] imageBytes = IOUtils.toByteArray(is); prest.setBytes(2, imageBytes); prest.setString(3, item.id); prest.execute(); prest.close(); }
From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java
/** * @return/* w w w .j a v a 2 s .c o m*/ * @throws IOException * @throws DomException * @throws BosMemberValidationException */ static Element getCommentTemplate(URL commentsUrl, BosConstructionOptions bosOptions) throws IOException, BosMemberValidationException, DomException { InputSource commentsTemplateXmlSource = new InputSource(commentsUrl.openStream()); commentsTemplateXmlSource.setSystemId(DocxConstants.COMMENTS_XML_PATH); Document commentsTemplateDom = DomUtil.getDomForSource(commentsTemplateXmlSource, bosOptions, false, false); NodeList comments = commentsTemplateDom.getDocumentElement() .getElementsByTagNameNS(DocxConstants.nsByPrefix.get("w"), "comment"); Element commentTemplate = (Element) comments.item(0); return commentTemplate; }
From source file:at.becast.youploader.database.SQLite.java
public static void insertPlaylist(Item item, int account) throws SQLException, IOException { PreparedStatement prest = null; String sql = "INSERT INTO `playlists` (`name`, `playlistid`,`image`,`account`,`shown`) " + "VALUES (?,?,?,?,1)"; prest = c.prepareStatement(sql);/* w ww . j a va2 s . c o m*/ prest.setString(1, item.snippet.title); prest.setString(2, item.id); URL url = new URL(item.snippet.thumbnails.default__.url); InputStream is = null; is = url.openStream(); byte[] imageBytes = IOUtils.toByteArray(is); prest.setBytes(3, imageBytes); prest.setInt(4, account); prest.execute(); prest.close(); }
From source file:com.t3.persistence.FileUtil.java
public static void unzip(URL url, File destDir) throws IOException { if (url == null) throw new IOException("URL cannot be null"); try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(url.openStream()))) { unzip(zis, destDir);//from w w w. ja v a2s. com } }
From source file:info.magnolia.cms.util.ConfigUtil.java
/** * Try to get the file. Get it first in the file system, then from the resources * @param fileName/*from w w w . j a v a 2 s . c om*/ * @return the input stream * @deprecated since 4.0 - use getTokenizedConfigFile */ public static InputStream getConfigFile(String fileName) { File file = new File(Path.getAppRootDir(), fileName); InputStream stream; // relative to webapp root if (file.exists()) { URL url; try { url = new URL("file:" + file.getAbsolutePath()); //$NON-NLS-1$ } catch (MalformedURLException e) { log.error("Unable to read config file from [" + fileName + "], got a MalformedURLException: ", e); return null; } try { stream = url.openStream(); } catch (IOException e) { log.error("Unable to read config file from [" + fileName + "], got a IOException ", e); return null; } return stream; } // try it directly file = new File(fileName); if (file.exists()) { try { stream = new FileInputStream(file); } catch (FileNotFoundException e) { log.error("Unable to read config file from [" + fileName + "], got a FileNotFoundException ", e); return null; } return stream; } // try resources try { return ClasspathResourcesUtil.getStream(fileName); } catch (IOException e) { log.error("Unable to read config file from the resources [" + fileName + "]", e); } return null; }
From source file:com.aurel.track.dbase.UpdateDbSchema.java
/** * Run an SQL script//from ww w.jav a 2s. c o m * @param script */ @SuppressWarnings("resource") private static void runSQLScript(String script, int maxValue, String progressText) { String folderName = getDbScriptFolder(); int line = 0; int noOfLines = 0; int progress = 0; Connection cono = null; try { long start = new Date().getTime(); cono = InitDatabase.getConnection(); cono.setAutoCommit(false); Statement ostmt = cono.createStatement(); script = "/dbase/" + folderName + "/" + script; URL populateURL = ApplicationBean.getInstance().getServletContext().getResource(script); InputStream in = populateURL.openStream(); java.util.Scanner s = new java.util.Scanner(in, "UTF-8").useDelimiter(";"); while (s.hasNext()) { ++noOfLines; s.nextLine(); } int mod = noOfLines / maxValue; in.close(); in = populateURL.openStream(); s = new java.util.Scanner(in, "UTF-8").useDelimiter(";"); String st = null; StringBuilder stb = new StringBuilder(); int modc = 0; progress = Math.round(new Float(mod) / new Float(noOfLines) * maxValue); LOGGER.info("Running SQL script " + script); while (s.hasNext()) { stb.append(s.nextLine().trim()); st = stb.toString(); ++line; ++modc; if (!st.isEmpty() && !st.startsWith("--") && !st.startsWith("/*") && !st.startsWith("#")) { if (st.trim().equalsIgnoreCase("go")) { try { cono.commit(); } catch (Exception ex) { LOGGER.error(ExceptionUtils.getStackTrace(ex)); } stb = new StringBuilder(); } else { if (st.endsWith(";")) { stb = new StringBuilder(); // clear buffer st = st.substring(0, st.length() - 1); // remove the semicolon try { if ("commit".equals(st.trim().toLowerCase()) || "go".equals(st.trim().toLowerCase())) { cono.commit(); } else { ostmt.executeUpdate(st); if (mod > 4 && modc >= mod) { modc = 0; ApplicationStarter.getInstance().actualizePercentComplete(progress, progressText); } } } catch (Exception exc) { if (!("Derby".equals(folderName) && exc.getMessage().contains("DROP TABLE") && exc.getMessage().contains("not exist"))) { LOGGER.error("Problem executing DDL statements: " + exc.getMessage()); LOGGER.error("Line " + line + ": " + st); } } } else { stb.append(" "); } } } else { stb = new StringBuilder(); } } in.close(); cono.commit(); cono.setAutoCommit(true); long now = new Date().getTime(); LOGGER.info("Database schema creation took " + (now - start) / 1000 + " seconds."); } catch (Exception e) { LOGGER.error("Problem upgrading database schema in line " + line + " of file " + script, e); } finally { try { if (cono != null) { cono.close(); } } catch (Exception e) { LOGGER.info("Closing the connection failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } }
From source file:at.becast.youploader.database.SQLite.java
public static void savePlaylists(Playlists playlists, int account) throws SQLException, IOException { PreparedStatement prest = null; String sql = "INSERT INTO `playlists` (`name`, `playlistid`,`image`,`account`) " + "VALUES (?,?,?,?)"; for (Playlists.Item i : playlists.items) { prest = c.prepareStatement(sql); prest.setString(1, i.snippet.title); prest.setString(2, i.id);/* w w w .ja v a 2 s. com*/ URL url = new URL(i.snippet.thumbnails.default__.url); InputStream is = null; is = url.openStream(); byte[] imageBytes = IOUtils.toByteArray(is); prest.setBytes(3, imageBytes); prest.setInt(4, account); prest.execute(); prest.close(); } }
From source file:gdt.data.grain.Support.java
/** * Get class resource as input stream. /* w ww . j a va 2 s. c o m*/ * @param handler the class * @param resource$ the resource name. * @return input stream. */ public static InputStream getClassResource(Class<?> handler, String resource$) { try { InputStream is = handler.getResourceAsStream(resource$); if (is != null) { //System.out.println("Support:getClassResource:resource stream="+is.toString()); return is; } else { // System.out.println("Support:getClassResource:cannot get embedded resource stream for handler="+handler.getName()); ClassLoader classLoader = handler.getClassLoader(); //if(classLoader!=null) // System.out.println("Support:getClassResource:class loader="+classLoader.toString()); is = classLoader.getResourceAsStream(resource$); //if(is!=null) // System.out.println("Support:getClassResource:resourse stream="+is.toString()); //else // System.out.println("Support:getClassResource:cannot get resource stream"); String handler$ = handler.getName(); //System.out.println("Support:getClassResource:class="+handler$); String handlerName$ = handler.getSimpleName(); //System.out.println("Support:getClassResource:class name="+handlerName$); String handlerPath$ = handler$.replace(".", "/"); //System.out.println("Support:getClassResource:class path="+handlerPath$); String resourcePath$ = "src/" + handlerPath$.replace(handlerName$, resource$); //System.out.println("Support:getClassResource:resource path="+resourcePath$); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); URL resourceUrl = classloader.getResource(resourcePath$); if (resourceUrl != null) { //System.out.println("Support:getClassResource:resource URL="+resourceUrl.toString()); return resourceUrl.openStream(); } else { //System.out.println("Support:getClassResource:cannot get resource URL"); } } } catch (Exception e) { Logger.getLogger(gdt.data.grain.Support.class.getName()).severe(e.toString()); } return null; }
From source file:name.yumao.douyu.http.PlaylistDownloader.java
private static void downloadInternal(URL segmentUrl, String outFile) { FileOutputStream out = null;/*from w w w . j av a 2 s .com*/ InputStream is = null; try { byte[] buffer = new byte[512]; is = segmentUrl.openStream(); if (outFile != null) { File file = new File(outFile); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } out = new FileOutputStream(outFile, file.exists()); } else { String path = segmentUrl.getPath(); int pos = path.lastIndexOf('/'); out = new FileOutputStream(path.substring(++pos), false); } logger.info("Downloading segment:" + segmentUrl + "\r"); int read; while ((read = is.read(buffer)) >= 0) { out.write(buffer, 0, read); } } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:eu.planets_project.services.utils.cli.CliMigrationPaths.java
/** * @param resourceName The XML file containing the path configuration * @return The paths defined in the XML file * @throws ParserConfigurationException// w w w .j av a 2 s . c o m * @throws IOException * @throws SAXException * @throws URISyntaxException */ // TODO: Clean up this exception-mess. Something like "InitialisationException" or "ConfigurationErrorException" should cover all these exceptions. public static CliMigrationPaths initialiseFromFile(String resourceName) throws ParserConfigurationException, IOException, SAXException, URISyntaxException { InputStream instream; ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL resourceURL = loader.getResource(resourceName); if (new File(defaultPath, resourceName).isFile()) { instream = new FileInputStream(new File(defaultPath, resourceName)); } else if (new File(resourceName).isFile()) { instream = new FileInputStream(new File(resourceName)); } else if (resourceURL != null) { instream = resourceURL.openStream(); } else { String msg = String.format("Could not locate resource %s", resourceName); throw new FileNotFoundException(msg); } CliMigrationPaths paths = new CliMigrationPaths(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(instream); Element fileformats = doc.getDocumentElement(); if (fileformats != null) { NodeList children = fileformats.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName().equals("path")) { CliMigrationPath pathdef = decodePathNode(child); paths.add(pathdef); } } } } IOUtils.closeQuietly(instream); return paths; }