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:com.quinsoft.zeidon.utils.JoeUtils.java

private static String computeHash(URL url) throws Exception {
    InputStream stream = url.openStream();
    try {/*from   www.  ja  va2s .  c  o m*/
        return DigestUtils.md5Hex(stream);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:com.redhat.rhn.testing.TestUtils.java

/**
 * Connect to <code>url</code> and return the contents
 * of that location as a string.//  ww w.  j a  va  2  s.  co  m
 *
 * @param url the URL to read from
 * @return the contents of the URL as a string, or <code>null</code>
 * if <code>url</code> is <code>null</code>
 * @throws IOException if reading the file fails
 */
public static String readAll(URL url) throws IOException {
    if (url == null) {
        return null;
    }
    return readAll(url.openStream());
}

From source file:com.moviejukebox.scanner.artwork.FanartScanner.java

public static boolean validateArtwork(IImage artworkImage, int artworkWidth, int artworkHeight,
        boolean checkAspect) {
    @SuppressWarnings("rawtypes")
    Iterator readers = ImageIO.getImageReadersBySuffix("jpeg");
    ImageReader reader = (ImageReader) readers.next();
    int urlWidth, urlHeight;
    float urlAspect;

    if (!ARTWORK_VALIDATE) {
        return true;
    }/* w w w.  j av a 2 s.c om*/

    if (StringTools.isNotValidString(artworkImage.getUrl())) {
        return false;
    }

    try {
        URL url = new URL(artworkImage.getUrl());

        try (InputStream in = url.openStream(); ImageInputStream iis = ImageIO.createImageInputStream(in)) {
            reader.setInput(iis, true);
            urlWidth = reader.getWidth(0);
            urlHeight = reader.getHeight(0);
        }
    } catch (IOException error) {
        LOG.debug("ValidateFanart error: {}: can't open url", error.getMessage());
        return false; // Quit and return a false fanart
    }

    urlAspect = (float) urlWidth / (float) urlHeight;

    if (checkAspect && urlAspect < 1.0) {
        LOG.debug("ValidateFanart {} rejected: URL is portrait format", artworkImage);
        return false;
    }

    // Adjust fanart width / height by the ValidateMatch figure
    int newArtworkWidth = artworkWidth * (ARTWORK_VALIDATE_MATCH / 100);
    int newArtworkHeight = artworkHeight * (ARTWORK_VALIDATE_MATCH / 100);

    if (urlWidth < newArtworkWidth) {
        LOG.debug("{} rejected: URL width ({}) is smaller than fanart width ({})", artworkImage, urlWidth,
                newArtworkWidth);
        return false;
    }

    if (urlHeight < newArtworkHeight) {
        LOG.debug("{} rejected: URL height ({}) is smaller than fanart height ({})", artworkImage, urlHeight,
                newArtworkHeight);
        return false;
    }
    return true;
}

From source file:com.beyondb.geocoding.BaiduAPI.java

/**
 * ????//www .  j  ava2 s.c  o m
 * ???? key lng(?),lat()
 * @param address
 * @param city
 * @return 
 */
public static Map<String, String> getLongLatCoordinate(String address, String city) {
    Map<String, String> map = new HashMap<>();
    try {
        //   ???utf-816 
        address = URLEncoder.encode(address, "UTF-8");
        //   ????? 
        //  System.setProperty("http.proxyHost","192.168.172.23"); 
        //  System.setProperty("http.proxyPort","3209"); 
        URL resjson = new URL("http://api.map.baidu.com/geocoder/v2/?ak=" + ak + "&output=json&address="
                + address + "&" + city);

        BufferedReader in = new BufferedReader(new InputStreamReader(resjson.openStream()));
        String res;
        StringBuilder sb = new StringBuilder("");
        while ((res = in.readLine()) != null) {
            sb.append(res.trim());
        }
        in.close();
        String str = sb.toString();
        System.out.println("return json:" + str);
        if (str.contains("lng")) {
            int lngStart = str.indexOf("lng\":");
            int lngEnd = str.indexOf(",\"lat");
            int latEnd = str.indexOf("},\"precise");
            if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
                String lng = str.substring(lngStart + 5, lngEnd);
                String lat = str.substring(lngEnd + 7, latEnd);
                map.put("lng", lng);
                map.put("lat", lat);
            }
        } else {
            map.put("lng", " ");
            map.put("lat", " ");
            Logger.getLogger(BaiduAPI.class.getName()).log(Level.WARNING,
                    "Parse coordinate from " + str + " is empty!");
            System.out.println("lng,lat is empty!" + str + "--" + map.get("lng") + "," + map.get("lat"));
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return map;
}

From source file:com.google.devrel.mobiledevicelab.spi.helper.DeviceLabApiHelper.java

/**
 * Calls Google account API to get the token information
 * //from   w ww.  j  a va2s. c o  m
 * @param accessToken
 * @return the JSON sent back by Google account API
 * @throws UnauthorizedException
 */
private static String getTokenJsonFromAccessToken(String accessToken) throws UnauthorizedException {
    String tokenJson = "";
    try {
        URL url = new URL("https://accounts.google.com/o/oauth2/tokeninfo?access_token=" + accessToken);
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String line;

        while ((line = reader.readLine()) != null) {
            tokenJson += line + "\n";
        }
        reader.close();
    } catch (MalformedURLException e) {
        throw new UnauthorizedException("We couldn't verify the access token with Google");
    } catch (IOException e) {
        throw new UnauthorizedException("We couldn't verify the access token with Google");
    }
    if (tokenJson.contains("invalid_token")) {
        throw new UnauthorizedException("The access token is invalid, please refresh the page");
    }
    return tokenJson;
}

From source file:com.nhn.android.archetype.base.object.BaseObj.java

public static <T extends BaseObj> T parse(URL url, Class<? extends BaseObj> clazz) throws Exception {
    InputStream is = url.openStream();

    try {/*  w ww  .jav  a2 s.c o  m*/
        return parse(is, clazz);
    } catch (Exception e) {
        throw e;
    } finally {
        try {
            if (is != null) {
                is.close();
                is = null;
            }
        } catch (Exception e) {
            logger.e(e);
        }
    }
}

From source file:com.swingtech.commons.util.ClassUtil.java

public static Object getObjectFromXML(final URL url) throws IOException {
    return getObjectFromXML(url.openStream());
}

From source file:com.mapviewer.business.NetCDFRequestManager.java

/**
 * This functions makes a URL request to one ncWMS server to retrieve the
 * valid animation options for the selected dates
 *
 * @param {Layer} layer/* w  w  w.j  ava2  s  .c  o  m*/
 * @param {String} startStr
 * @param {String} endStr
 * @return
 */
public static String getLayerTimeStepsForAnimation(Layer layer, String startStr, String endStr) {

    URL ncReq;
    String urlRequest = buildRequest(layer, "GetMetadata", "animationTimesteps");
    urlRequest += "&start=" + startStr;
    urlRequest += "&end=" + endStr;

    JSONObject timeSteps = new JSONObject();

    try {
        ncReq = new URL(urlRequest);
        ncReq.openConnection();
        InputStreamReader input = new InputStreamReader(ncReq.openStream());
        BufferedReader in = new BufferedReader(input);
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            if (!inputLine.trim().equalsIgnoreCase("")) {// TODO check for errros
                timeSteps = new JSONObject(inputLine);

                //               datesWithData = (JSONObject) layerDetails.get("datesWithData");
                /*
                 * //Iterating over the years for(Enumeration years =
                 * dates.keys(); years.hasMoreElements();){ String year =
                 * (String) years.nextElement(); JSONObject yearJson =
                 * dates.getJSONObject(year); for(Enumeration months =
                 * yearJson.keys(); months.hasMoreElements();){ String month
                 * = (String) months.nextElement(); int x = 1; } }
                 */
            }
        }

    } catch (JSONException | IOException e) {
        System.out.println("Error MapViewer en RedirectServer en generateRedirect" + e.getMessage());
        return "Error getting the layerDetials:" + e.getMessage();
    }
    return timeSteps.toString();
}

From source file:com.utest.webservice.client.rest.AuthSSLProtocolSocketFactory.java

private static KeyStore createKeyStore(final URL url, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    if (url == null) {
        throw new IllegalArgumentException("Keystore url may not be null");
    }/*  w ww.  j av  a 2 s.  co  m*/
    KeyStore keystore = KeyStore.getInstance("jks");
    InputStream is = null;
    try {
        is = url.openStream();
        keystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }
    return keystore;
}

From source file:com.google.dart.tools.update.core.internal.UpdateUtils.java

/**
 * Read, as a string, the stream at the given url string.
 *//*ww  w . ja  v a 2 s .c  o m*/
public static String readUrlStream(String urlString) throws MalformedURLException, IOException {
    URL url = new URL(urlString);
    InputStream stream = url.openStream();
    return toString(stream);
}