List of usage examples for java.net URL openStream
public final InputStream openStream() throws java.io.IOException
From source file:com.arm.connector.bridge.core.Utils.java
public static String getExternalIPAddress() { if (Utils._externalIPAddress == null) { BufferedReader in = null; try {/*from www.ja v a 2 s . co m*/ URL whatismyip = new URL("http://checkip.amazonaws.com"); in = new BufferedReader(new InputStreamReader(whatismyip.openStream())); Utils._externalIPAddress = in.readLine(); in.close(); } catch (Exception ex) { try { if (in != null) in.close(); } catch (Exception ex2) { // silent } } } return Utils._externalIPAddress; }
From source file:edu.isi.karma.kr2rml.mapping.WorksheetR2RMLJenaModelParser.java
public static Model loadSourceModelIntoJenaModel(R2RMLMappingIdentifier id) throws IOException { // Create an empty Model Model model = ModelFactory.createDefaultModel(); InputStream s;// w w w. ja v a 2 s. c o m if (id.getContent() != null) { s = IOUtils.toInputStream(id.getContent()); } else { URL modelURL = id.getLocation(); logger.info("Load model:" + modelURL.toString()); s = modelURL.openStream(); } model.read(s, null, "TURTLE"); return model; }
From source file:eu.medsea.mimeutil.detector.ExtensionMimeDetector.java
private static void initMimeTypes() { InputStream is = null;/*from w w w. j a v a 2 s. co m*/ extMimeTypes = new Properties(); try { // Load the file extension mappings from the internal property file and // then // from the custom property files if they can be found try { // Load the default supplied mime types is = MimeUtil.class.getClassLoader() .getResourceAsStream("eu/medsea/mimeutil/mime-types.properties"); if (is != null) { ((Properties) extMimeTypes).load(is); } } catch (Exception e) { // log the error but don't throw the exception up the stack log.error("Error loading internal mime-types.properties", e); } finally { is = closeStream(is); } // Load any .mime-types.properties from the users home directory try { File f = new File(System.getProperty("user.home") + File.separator + ".mime-types.properties"); if (f.exists()) { is = new FileInputStream(f); if (is != null) { log.debug("Found a custom .mime-types.properties file in the users home directory."); Properties props = new Properties(); props.load(is); if (props.size() > 0) { extMimeTypes.putAll(props); } log.debug("Successfully parsed .mime-types.properties from users home directory."); } } } catch (Exception e) { log.error("Failed to parse .magic.mime file from users home directory. File will be ignored.", e); } finally { is = closeStream(is); } // Load any classpath provided mime types that either extend or // override the default mime type entries. Could also be in jar files. // Get an enumeration of all files on the classpath with this name. They could be in jar files as well try { Enumeration e = MimeUtil.class.getClassLoader().getResources("mime-types.properties"); while (e.hasMoreElements()) { URL url = (URL) e.nextElement(); if (log.isDebugEnabled()) { log.debug("Found custom mime-types.properties file on the classpath [" + url + "]."); } Properties props = new Properties(); try { is = url.openStream(); if (is != null) { props.load(is); if (props.size() > 0) { extMimeTypes.putAll(props); if (log.isDebugEnabled()) { log.debug("Successfully loaded custome mime-type.properties file [" + url + "] from classpath."); } } } } catch (Exception ex) { log.error("Failed while loading custom mime-type.properties file [" + url + "] from classpath. File will be ignored."); } } } catch (Exception e) { log.error( "Problem while processing mime-types.properties files(s) from classpath. Files will be ignored.", e); } finally { is = closeStream(is); } try { // Load any mime extension mappings file defined with the JVM // property -Dmime-mappings=../my/custom/mappings.properties String fname = System.getProperty("mime-mappings"); if (fname != null && fname.length() != 0) { is = new FileInputStream(fname); if (is != null) { if (log.isDebugEnabled()) { log.debug( "Found a custom mime-mappings property defined by the property -Dmime-mappings [" + System.getProperty("mime-mappings") + "]."); } Properties props = new Properties(); props.load(is); if (props.size() > 0) { extMimeTypes.putAll(props); } log.debug("Successfully loaded the mime mappings file from property -Dmime-mappings [" + System.getProperty("mime-mappings") + "]."); } } } catch (Exception ex) { log.error("Failed to load the mime-mappings file defined by the property -Dmime-mappings [" + System.getProperty("mime-mappings") + "]."); } finally { is = closeStream(is); } } finally { // Load the mime types into the known mime types map of MimeUtil Iterator it = extMimeTypes.values().iterator(); while (it.hasNext()) { String[] types = ((String) it.next()).split(","); for (int i = 0; i < types.length; i++) { MimeUtil.addKnownMimeType(types[i]); } } } }
From source file:net.ftb.util.DownloadUtils.java
/** * Downloads data from the given URL and saves it to the given file * @param url The url to download from//from www. j a v a 2 s . c o m * @param file The file to save to. * * TODO: how to handle partial downloads? Old file is overwritten as soon as FileOutputStream is created. */ public static void downloadToFile(URL url, File file) throws IOException { file.getParentFile().mkdirs(); ReadableByteChannel rbc = Channels.newChannel(url.openStream()); FileOutputStream fos = new FileOutputStream(file); fos.getChannel().transferFrom(rbc, 0, 1 << 24); fos.close(); }
From source file:com.eurotong.orderhelperandroid.Common.java
public static String downloadContentFromInternet(String urlString) throws IOException { /*//ww w . ja v a 2 s. com URLConnection feedUrl=null; try { feedUrl = new URL(url).openConnection(); } catch (MalformedURLException e) { Log.v("ERROR","MALFORMED URL EXCEPTION"); } catch (IOException e) { e.printStackTrace(); } try { InputStream in = feedUrl.getInputStream(); String json = convertStreamToString(in); return json; } catch(Exception e){} return null; */ //http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); Date date = new Date(); String datetime = dateFormat.format(date); // Create a URL for the desired page URL url = new URL(urlString + "?d=" + datetime); // Read all the text returned by the server InputStream in = url.openStream(); String content = convertStreamToString(in); return content; }
From source file:com.inamik.template.util.TemplateConfigUtil.java
/** * readTemplateEngineConfig w/URL - Read a template engine xml * configuration from a URL.//from w w w . j a v a 2s . c om * <p> * This is a convenience method and is equivelent to: * <p> * <code>readTeplateEngineConfig(url.oipenStream())</code> * * @param url The URL to read. * @return A template engine configuration suitable for instantiating * a TemplateEngine class. * @throws IOException * @throws TemplateException * @throws NullPointerException if <code>url == null</code> * * @see #readTemplateEngineConfig(InputStream) */ public static TemplateEngineConfig readTemplateEngineConfig(final URL url) throws IOException, TemplateException { if (url == null) { throw new NullPointerException("url"); } return readTemplateEngineConfig(url.openStream()); }
From source file:io.github.seanboyy.lotReset.json.ReadJSON.java
/**Read JSON file by using configuration file's JSON value, * which points to the file// w w w. j a v a 2s .c o m * @param configLocation String which specifies the location of the config.properties file * @return <code>ArrayList<ArrayList<Lot>> lots</code> if no errors are encountered * @since 1.0 - Implemented config.properties in 2.0 */ public static ArrayList<ArrayList<Lot>> read(String configLocation) { JSONParser parser = new JSONParser(); URL url; File f; //lots is multidimensional in this format: {{fromLot,toLot},{fromLot,toLot},{fromLot,toLot},etc...} ArrayList<ArrayList<Lot>> lots = new ArrayList<ArrayList<Lot>>(); Config config = ReadConfig.read(configLocation); final String[] alphabet = config.getAlpha(); final String[] types = config.getType(); final String[] worlds = config.getWorld(); try { url = new URL(config.getJSON()); InputStream in = url.openStream(); f = File.createTempFile("temp", "json"); FileWriter file = new FileWriter(f); Scanner input = new Scanner(in); while (input.hasNextLine()) { file.write(input.nextLine()); } input.close(); file.close(); Object obj = parser.parse(new FileReader(f)); JSONObject jsonObj = (JSONObject) obj; JSONObject regions = (JSONObject) jsonObj.get("Regions"); for (String a : worlds) { for (String b : types) { for (String c : alphabet) { for (int d = 1; d <= alphabet.length; ++d) { String lotId = a + "-" + b + "-" + c + d; String lotIdA = a + "_" + b + "-" + c + d; String lotIdB = a + "-" + b + "_" + c + d; String lotIdC = a + "_" + b + "_" + c + d; JSONObject lot = (JSONObject) regions.get(lotId); JSONObject lotA = (JSONObject) regions.get(lotIdA); JSONObject lotB = (JSONObject) regions.get(lotIdB); JSONObject lotC = (JSONObject) regions.get(lotIdC); ArrayList<Lot> lotInfo = new ArrayList<Lot>(); if (lot != null) { lotInfo.add(new Lot((long) lot.get("source_minX"), (long) lot.get("source_maxX"), (long) lot.get("source_minY"), (long) lot.get("source_maxY"), (long) lot.get("source_minZ"), (long) lot.get("source_maxZ"), (String) lot.get("source_file"), lotId)); lotInfo.add(new Lot((long) lot.get("dest_minX"), (long) lot.get("dest_maxX"), (long) lot.get("dest_minY"), (long) lot.get("dest_maxY"), (long) lot.get("dest_minZ"), (long) lot.get("dest_maxZ"), (String) lot.get("dest_file"), lotId)); lots.add(lotInfo); } if (lotA != null) { lotInfo.add(new Lot((long) lotA.get("source_minX"), (long) lotA.get("source_maxX"), (long) lotA.get("source_minY"), (long) lotA.get("source_maxY"), (long) lotA.get("source_minZ"), (long) lotA.get("source_maxZ"), (String) lotA.get("source_file"), lotIdA)); lotInfo.add(new Lot((long) lotA.get("dest_minX"), (long) lotA.get("dest_maxX"), (long) lotA.get("dest_minY"), (long) lotA.get("dest_maxY"), (long) lotA.get("dest_minZ"), (long) lotA.get("dest_maxZ"), (String) lotA.get("dest_file"), lotIdA)); lots.add(lotInfo); } if (lotB != null) { lotInfo.add(new Lot((long) lotB.get("source_minX"), (long) lotB.get("source_maxX"), (long) lotB.get("source_minY"), (long) lotB.get("source_maxY"), (long) lotB.get("source_minZ"), (long) lotB.get("source_maxZ"), (String) lotB.get("source_file"), lotIdB)); lotInfo.add(new Lot((long) lotB.get("dest_minX"), (long) lotB.get("dest_maxX"), (long) lotB.get("dest_minY"), (long) lotB.get("dest_maxY"), (long) lotB.get("dest_minZ"), (long) lotB.get("dest_maxZ"), (String) lotB.get("dest_file"), lotIdB)); lots.add(lotInfo); } if (lotC != null) { lotInfo.add(new Lot((long) lotC.get("source_minX"), (long) lotC.get("source_maxX"), (long) lotC.get("source_minY"), (long) lotC.get("source_maxY"), (long) lotC.get("source_minZ"), (long) lotC.get("source_maxZ"), (String) lotC.get("source_file"), lotIdC)); lotInfo.add(new Lot((long) lotC.get("dest_minX"), (long) lotC.get("dest_maxX"), (long) lotC.get("dest_minY"), (long) lotC.get("dest_maxY"), (long) lotC.get("dest_minZ"), (long) lotC.get("dest_maxZ"), (String) lotC.get("dest_file"), lotIdC)); lots.add(lotInfo); } } } } } } catch (IOException e) { System.out.println("FILE ERROR FROM READING JSON"); e.printStackTrace(); return null; } catch (ParseException e) { System.out.println("PARSER ERROR FROM READING JSON"); e.printStackTrace(); return null; } return lots; }
From source file:com.moviejukebox.tools.DOMHelper.java
/** * Get a DOM document from the supplied file * * @param xmlFile//from ww w .java2 s. co m * @return * @throws IOException * @throws ParserConfigurationException * @throws SAXException */ public static Document getDocFromFile(File xmlFile) throws ParserConfigurationException, SAXException, IOException { URL url = xmlFile.toURI().toURL(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc; // Custom error handler db.setErrorHandler(new SaxErrorHandler()); try (InputStream in = url.openStream()) { doc = db.parse(in); } catch (SAXParseException ex) { if (FilenameUtils.isExtension(xmlFile.getName().toLowerCase(), "xml")) { throw new SAXParseException("Failed to process file as XML", null, ex); } // Try processing the file a different way doc = null; } if (doc == null) { try ( // try wrapping the file in a root StringReader sr = new StringReader(wrapInXml(FileTools.readFileToString(xmlFile)))) { doc = db.parse(new InputSource(sr)); } } if (doc != null) { doc.getDocumentElement().normalize(); } return doc; }
From source file:kenh.xscript.ScriptUtils.java
/** * Get xScript instance./* w w w .j av a 2 s . c o m*/ * @param url * @param env * @return * @throws UnsupportedScriptException */ public static final Element getInstance(URL url, Environment env) throws UnsupportedScriptException { if (url == null) return null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true); factory.setNamespaceAware(true); factory.setIgnoringElementContentWhitespace(true); InputStream in = url.openStream(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(in); return getInstance(doc, env); } catch (UnsupportedScriptException e) { throw e; } catch (Exception e) { throw new UnsupportedScriptException(null, e); } }
From source file:org.apache.cxf.dosgi.dsw.OsgiUtils.java
@SuppressWarnings("unchecked") public static List<Element> getAllDescriptionElements(Bundle b) { Object directory = null;/*from w w w .ja v a 2 s .c om*/ Dictionary headers = b.getHeaders(); if (headers != null) { directory = headers.get(REMOTE_SERVICES_HEADER_NAME); } if (directory == null) { directory = REMOTE_SERVICES_DIRECTORY; } Enumeration urls = b.findEntries(directory.toString(), "*.xml", false); if (urls == null) { return Collections.emptyList(); } List<Element> elements = new ArrayList<Element>(); while (urls.hasMoreElements()) { URL resourceURL = (URL) urls.nextElement(); try { Document d = new SAXBuilder().build(resourceURL.openStream()); Namespace ns = Namespace.getNamespace(REMOTE_SERVICES_NS); elements.addAll(d.getRootElement().getChildren(SERVICE_DESCRIPTION_ELEMENT, ns)); } catch (Exception ex) { LOG.log(Level.WARNING, "Problem parsing: " + resourceURL, ex); } } return elements; }