Example usage for java.net URL openStream

List of usage examples for java.net URL openStream

Introduction

In this page you can find the example usage for java.net URL openStream.

Prototype

public final InputStream openStream() throws java.io.IOException 

Source Link

Document

Opens a connection to this URL and returns an InputStream for reading from that connection.

Usage

From source file:it.damore.solr.importexport.App.java

/**
 * @param sUrl/* ww w. j  a  va 2s.  co  m*/
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
private static String readUrl(String sUrl) throws MalformedURLException, IOException {
    StringBuilder sbJson = new StringBuilder();
    URL url = new URL(sUrl);
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null)
        sbJson.append(inputLine);
    in.close();
    return sbJson.toString();
}

From source file:Models.Taxonomy.Repository.RepositoryTNRS.java

/**
 * Method that consuming web services from tnrs and get results
 * @param name Name from specie to evaluate
 * @param best True for best results, false if all results
 * @return /* ww w. ja va 2 s  .c  o  m*/
 */
public static TNRS[] get(String name, boolean best) {
    TNRS[] a = null;
    try {
        if (db == null)
            db = new HashMap();
        if (db.containsKey(name.trim().replaceAll(" ", "_")))
            return (TNRS[]) db.get(name.trim().replaceAll(" ", "_"));
        URL url = new URL(Configuration.getParameter("tnrs_url_base")
                + (best ? "retrieve=best" : "retrieve=all") + "&names=" + name.replaceAll(" ", "%20"));
        BufferedReader lector = new BufferedReader(new InputStreamReader(url.openStream()));
        String textJson = lector.readLine();
        if (textJson == null)
            throw new Exception("Don't found item " + name);
        JSONArray jsNames = (JSONArray) ((JSONObject) JSONValue.parse(textJson)).get("items");
        a = new TNRS[jsNames.size()];
        for (int i = 0; i < a.length; i++)
            a[i] = new TNRS((JSONObject) jsNames.get(i));
        db.put(name.trim().replaceAll(" ", "_"), a);
    } catch (Exception ex) {
        a = null;
        System.out.println("Error TNRS: " + ex);
    }
    return a;
}

From source file:Main.java

public static Bitmap urlToBitmap(String siteUrl, int requireSize) {
    //Log.d(LOG_TAG, "call the urlToBitmap " + ++callTime); // called 8 times..

    if (siteUrl == null) {
        //Log.d(LOG_TAG, "the url is null, throw Exception");
        return null;
    }/*  w  ww  .  j  a  v  a  2  s.  c o  m*/

    URL url;
    try {
        url = new URL(siteUrl);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(url.openStream(), null, options);

        // determinte the scale size
        int scale = 1;
        //Log.d(Constant.LOG_TAG, "the outHeight is " + options.outHeight + ", the outWidth is " + options.outWidth);

        scale = computeSampleSize(options, -1, requireSize * requireSize);
        options.inJustDecodeBounds = false;
        //Log.d(Constant.LOG_TAG, "the scale is " + scale);
        options.inSampleSize = scale;
        Bitmap bitmap = BitmapFactory.decodeStream(url.openStream(), null, options);
        //Log.d(LOG_TAG, "get the bitmap in urltobitmap " + callTime);
        return bitmap;
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //Log.d(LOG_TAG, "return null in urltobitmap " + callTime);
    return null;

}

From source file:net.ftb.util.AppUtils.java

public static String getExternalIP() {
    try {//from  www .j a  v  a  2  s . c o m
        URL url = new URL("http://checkip.amazonaws.com");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        return in.readLine();
    } catch (Exception e) {
        Logger.logDebug("failed", e);
    }
    return null;
}

From source file:com.sunchenbin.store.feilong.core.net.URLUtil.java

/**
 * ./*from   ww  w . ja  va 2 s. c o  m*/
 * 
 * <p>
 * ??? .
 * </p>
 *
 * @param urlString
 *            ?<br>
 *            url ??
 * @param directoryName
 *            
 * @throws IOException
 *             the IO exception
 * @see IOWriteUtil#write(InputStream, String, String)
 * 
 * @see org.apache.commons.io.FileUtils#copyURLToFile(URL, File)
 * @see org.apache.commons.io.FileUtils#copyURLToFile(URL, File, int, int)
 * 
 */
public static void download(String urlString, String directoryName) throws IOException {
    if (Validator.isNullOrEmpty(urlString)) {
        throw new NullPointerException("urlString can't be null/empty!");
    }
    if (Validator.isNullOrEmpty(directoryName)) {
        throw new NullPointerException("directoryName can't be null/empty!");
    }

    LOGGER.info("begin download,urlString:[{}],directoryName:[{}]", urlString, directoryName);

    URL url = URLUtil.newURL(urlString);
    InputStream inputStream = url.openStream();

    File file = new File(urlString);
    String fileName = file.getName();

    IOWriteUtil.write(inputStream, directoryName, fileName);

    LOGGER.info("end download,url:[{}],directoryName:[{}]", urlString, directoryName);
}

From source file:de.nava.informa.utils.FormatDetector.java

/**
 * Guess the format of the specified news channel. For performance
 * reason it is wise to minimize the number of format guesses.
 *
 * @param url a url to the news channel.
 * @return The news channel synatx format, currently only RSS 0.91
 * ({@link de.nava.informa.core.ChannelFormat#RSS_0_91})
 * and RSS/RDF 1.0//  w w w  .ja v a 2s .c  o m
 * ({@link de.nava.informa.core.ChannelFormat#RSS_1_0})
 * are recognized.
 * @throws UnsupportedFormatException in case a news channel format
 *                                    could not be guessed.
 * @throws IOException                if the given url cannot be read in.
 */
public static ChannelFormat getFormat(URL url) throws IOException, UnsupportedFormatException {

    logger.info("Trying to retrieve stream from " + url);
    BufferedInputStream in = new BufferedInputStream(url.openStream(), NR_FIRST_BYTES);
    return getFormat(in);
}

From source file:com.ericsson.eiffel.remrem.generate.EiffelRemremControllerIntegrationTest.java

public static String getMessagingVersion() {
    Enumeration resEnum;/*w ww  .j  a va2s  .c om*/
    try {
        resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
        while (resEnum.hasMoreElements()) {
            try {
                URL url = (URL) resEnum.nextElement();
                if (url.getPath().contains("eiffel-remrem-semantics")) {
                    InputStream is = url.openStream();
                    if (is != null) {
                        Manifest manifest = new Manifest(is);
                        Attributes mainAttribs = manifest.getMainAttributes();
                        String version = mainAttribs.getValue("semanticsVersion");
                        if (version != null) {
                            return version;
                        }
                    }
                }
            } catch (Exception e) {
                // Silently ignore wrong manifests on classpath?
            }
        }
    } catch (IOException e1) {
        // Silently ignore wrong manifests on classpath?
    }
    return null;
}

From source file:it.attocchi.utils.HtmlUtils.java

/**
 * /*from w ww  .j a v a2s  .co  m*/
 * @param uri
 * @return
 * @throws Exception
 */
// public static String readUrl(String uri) throws Exception {
// StringBuilder sb = new StringBuilder();
// URL url = new URL(uri);
// BufferedReader in = new BufferedReader(new
// InputStreamReader(url.openStream()));
//
// String inputLine;
// while ((inputLine = in.readLine()) != null) {
// sb.append(inputLine);
// }
// in.close();
//
// return sb.toString();
// }

public static String callUrl(String url) throws Exception {
    StringBuffer sb = new StringBuffer();

    // try {

    if (StringUtils.isNotEmpty(url)) {
        URL anUrl = new URL(url);
        BufferedReader in = new BufferedReader(new InputStreamReader(anUrl.openStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            // System.out.println(inputLine);
            sb.append(inputLine);
        }
        in.close();
    }

    // } catch (Exception ex) {
    // // logger.error("callProc", ex);
    // }

    return sb.toString();
}

From source file:Main.java

public static Node loadURL(java.net.URL url) {
    Document document = null;/* w  ww  .jav  a2  s  .com*/
    if (url != null) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            document = builder.parse(url.openStream());
        } catch (java.io.IOException ioe) {
            document = null;
            ioe.printStackTrace();
        } catch (ParserConfigurationException pce) {
            document = null;
            pce.printStackTrace();
        } catch (org.xml.sax.SAXException se) {
            document = null;
            se.printStackTrace();
        }

        return document;
    }
    return null;
}

From source file:eu.aniketos.ncvm.impl.EncodeSupport.java

static Map<String, String> LoadKeyValueFile(String file) throws IOException {
    Map<String, String> keyValues = new HashMap<String, String>();
    keyValues.clear();/*from  w  ww . j a  v  a2 s. c om*/

    BundleContext context = Activator.getContext();
    // Load data from the configuration file if there is one
    System.out.println("Reading key-value pairs from: " + file);
    URL configURL = context.getBundle().getEntry(file);
    if (configURL != null) {
        // Read the key value pairs
        BufferedReader input = new BufferedReader(new InputStreamReader(configURL.openStream()));
        try {
            String read = "";
            while (read != null) {
                read = input.readLine();
                // Skip comments and blank lines
                if ((read != null) && (!read.isEmpty()) && (!read.startsWith("#"))) {
                    // Read in the key-value pair
                    int separator = read.indexOf('=');
                    if (separator >= 0) {
                        String key = read.substring(0, separator).trim().toLowerCase();
                        String value = read.substring(separator + 1).trim();
                        // Store the result in our map
                        keyValues.put(key, value);
                    }
                }
            }
        } finally {
            input.close();
        }
    }

    return keyValues;
}