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:cc.gospy.core.util.StringHelper.java

public static String getMyExternalIp() {
    if (myExternalIp == null) {
        try {//from ww  w  . j  a  va 2s.  c o  m
            logger.info("Querying external ip...");
            FutureTask futureTask = new FutureTask<>(() -> {
                URL ipEcho = new URL("http://ipecho.net/plain");
                BufferedReader in = new BufferedReader(new InputStreamReader(ipEcho.openStream()));
                String resultIp = in.readLine();
                in.close();
                return resultIp;
            });
            futureTask.run();
            myExternalIp = (String) futureTask.get(3, TimeUnit.SECONDS);
            logger.info("My external ip: {}", myExternalIp);
        } catch (TimeoutException e) {
            myExternalIp = "unknown ip";
            logger.error("Get external ip failure, cause: Timeout (3 seconds)");
        } catch (Exception e) {
            myExternalIp = "unknown ip";
            logger.error("Get external ip failure, cause: {}", e.getMessage());
        }
    }
    return myExternalIp;
}

From source file:com.github.srec.util.ResourceFactory.java

public static String digestResource(URL url) throws NoSuchAlgorithmException, IOException {
    MessageDigest digest = MessageDigest.getInstance("SHA");
    InputStream is = url.openStream();
    byte[] buffer = new byte[8192];
    int read = 0;
    try {/*from   www. j a v a  2s  . co m*/
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] shaSum = digest.digest();
        return new BigInteger(1, shaSum).toString(16);
    } catch (IOException e) {
        throw new RuntimeException("Unable to process file for MD5", e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            throw new RuntimeException("Unable to close input stream for MD5 calculation", e);
        }
    }
}

From source file:de.cosmocode.palava.core.AsciiArt.java

private static InputStream open() throws IOException {
    final File file = new File("lib", FILE_NAME);
    final URL resource = AsciiArt.class.getClassLoader().getResource(FILE_NAME);

    if (file.exists()) {
        return new FileInputStream(file);
    } else {/* w  w w.j ava 2  s  . com*/
        if (resource == null) {
            throw new FileNotFoundException(String.format("classpath:%s", FILE_NAME));
        }
        return resource.openStream();
    }
}

From source file:com.blacklocus.jres.Jres.java

public static <T> T load(URL script, TypeReference<T> typeReference) {
    try {//  w ww .j  a va2s  .  com
        // Don't use ObjectMapper.readValue(URL, ?), doesn't seem to be able to find local resources.
        return ObjectMappers.fromJson(script.openStream(), typeReference);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.turt2live.hurtle.uuid.UUIDServiceProvider.java

/**
 * Gets the name of a player for the specified UUID.
 *
 * @param uuid the uuid to lookup, cannot be null
 *
 * @return the player's name, or null if not found or for invalid input
 *///from  ww  w. j a v a 2 s  .co  m
public static String getName(UUID uuid) {
    if (uuid == null)
        return null;
    try {
        URL url = new URL("http://uuid.turt2live.com/name/" + uuid.toString().replaceAll("-", ""));
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String parsed = "";
        String line;
        while ((line = reader.readLine()) != null)
            parsed += line;
        reader.close();

        Object o = JSONValue.parse(parsed);
        if (o instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) o;
            Object status = jsonObject.get("status");
            if (status instanceof String && ((String) status).equalsIgnoreCase("ok")) {
                o = jsonObject.get("name");
                if (o instanceof String) {
                    return (String) o;
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:net.ageto.gyrex.impex.persistence.cassandra.ConfigureRepositoryPreferences.java

/**
 * Read repository Properties from supplied uri and apply them to the
 * Repository configuration/* ww  w .  ja  v  a 2  s.co m*/
 *
 * @param url
 * @param cassandraRepositoryId
 */
public static void readRepositoryPreferences(final URL url, final String cassandraRepositoryId,
        IRuntimeContext context) {

    assignDedicatedCassandraRepositories(context, cassandraRepositoryId);

    InputStream stream = null;

    try {
        stream = url.openStream();
        final Properties p = new Properties();
        p.load(stream);

        createRepositoryStore(cassandraRepositoryId, CassandraRepositoryProvider.ID);

        IRepositoryRegistry repositoryRegistry = ImpexCassandraActivator.getInstance().getRepositoryRegistry();

        IRepositoryPreferences repositoryPreferences = repositoryRegistry
                .getRepositoryDefinition(cassandraRepositoryId).getRepositoryPreferences();

        // Cassandra configuration
        getAndSetProperty(p, ICassandraRepositoryConstants.CONF_CLUSTER_NAME, repositoryPreferences);
        getAndSetProperty(p, ICassandraRepositoryConstants.CONF_CASSANDRA_HOST, repositoryPreferences);
        getAndSetProperty(p, ICassandraRepositoryConstants.CONF_KEYSPACE_NAME, repositoryPreferences);
        getAndSetProperty(p, ICassandraRepositoryConstants.CONF_COLUMN_FAMILY_PROCESSES, repositoryPreferences);
        getAndSetProperty(p, ICassandraRepositoryConstants.CONF_COLUMN_NAME_PROCESS, repositoryPreferences);
        getAndSetProperty(p, ICassandraRepositoryConstants.CONF_SUPERCOLUMN_FAMILY_PROCESS_LOGGING,
                repositoryPreferences);
        getAndSetProperty(p, ICassandraRepositoryConstants.CONF_COLUMN_NAME_LOGLEVEL, repositoryPreferences);
        getAndSetProperty(p, ICassandraRepositoryConstants.CONF_COLUMN_NAME_MESSAGE, repositoryPreferences);

        repositoryPreferences.flush();
        // } catch (final FileNotFoundException e) {
        // throw new IllegalStateException("Cannot read from " + url, e);
        // } catch (final IOException e) {
        // throw new IllegalStateException("Cannot read from " + url, e);
    } catch (final Exception e) {
        LOG.error("Error while stroring preferences for repository: " + e, e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:com.sheepdog.mashmesh.Itinerary.java

public static Itinerary fetch(String fromLocation, String toLocation, String viaLocation, DateTime arrivalTime)
        throws URISyntaxException, IOException {
    URIBuilder uriBuilder = new URIBuilder(DIRECTIONS_ENDPOINT_URL);
    uriBuilder.addParameter("origin", fromLocation);
    uriBuilder.addParameter("destination", toLocation);
    uriBuilder.addParameter("mode", "driving");
    uriBuilder.addParameter("language", "en_US"); // TODO: Configurable?
    uriBuilder.addParameter("region", "us");
    uriBuilder.addParameter("waypoints", viaLocation);
    uriBuilder.addParameter("sensor", "false");

    URL url = uriBuilder.build().toURL();
    BufferedReader responseReader = new BufferedReader(new InputStreamReader(url.openStream()));

    JsonParser parser = new JsonParser();
    JsonObject responseObject = parser.parse(responseReader).getAsJsonObject();
    JsonObject route = responseObject.getAsJsonArray("routes").get(0).getAsJsonObject();
    JsonArray legs = route.getAsJsonArray("legs");

    JsonObject startLeg = legs.get(0).getAsJsonObject();
    JsonObject endLeg = legs.get(legs.size() - 1).getAsJsonObject();

    DateTime departureTime = arrivalTime;
    List<Leg> directionLegs = new ArrayList<Leg>();

    Preconditions.checkState(legs.size() == 2, "Expected two direction legs in response");

    // Process the legs in reverse order so that we can compute departure and arrival
    //  times by working backwards from the desired arrival time.
    for (int i = legs.size() - 1; i >= 0; i--) {
        JsonObject leg = legs.get(i).getAsJsonObject();
        List<Step> directionSteps = new ArrayList<Step>();
        DateTime legArrivalTime = departureTime;

        for (JsonElement stepElement : leg.getAsJsonArray("steps")) {
            JsonObject stepObject = stepElement.getAsJsonObject();
            int duration = stepObject.getAsJsonObject("duration").get("value").getAsInt();
            String htmlInstructions = stepObject.get("html_instructions").getAsString();
            String distance = stepObject.getAsJsonObject("distance").get("text").getAsString();

            departureTime = departureTime.minusSeconds(duration);
            directionSteps.add(new Step(htmlInstructions, distance));
        }//from   w  w  w . j  a  va  2s  .  c  o  m

        Leg directionLeg = new Leg();
        directionLeg.departureTime = departureTime;
        directionLeg.startLatLng = getLatLng(leg.getAsJsonObject("start_location"));
        directionLeg.arrivalTime = legArrivalTime;
        directionLeg.endLatLng = getLatLng(leg.getAsJsonObject("end_location"));
        directionLeg.distanceMeters = leg.getAsJsonObject("distance").get("value").getAsInt();
        directionLeg.steps = Collections.unmodifiableList(directionSteps);
        directionLegs.add(directionLeg);
    }

    Collections.reverse(directionLegs);

    Itinerary itinerary = new Itinerary();
    itinerary.startAddress = startLeg.get("start_address").getAsString();
    itinerary.endAddress = endLeg.get("end_address").getAsString();
    itinerary.legs = Collections.unmodifiableList(directionLegs);
    itinerary.overviewPolyline = route.getAsJsonObject("overview_polyline").get("points").getAsString();

    return itinerary;
}

From source file:json.JsonUI.java

private static String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {// ww w  .  ja v  a2 s . c  o  m
        URL url = new URL(urlString);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuilder buffer = new StringBuilder();
        int read;
        while ((read = reader.read()) != -1) {
            buffer.append((char) read);
        }
        return buffer.toString();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.asakusafw.shafu.core.net.ShafuNetwork.java

/**
 * Processes a content on the target URL.
 * @param url the target URL/*  w  w  w . j  av  a  2s  .com*/
 * @param processor the content processor
 * @param <T> the processing result type
 * @return the process result
 * @throws IOException if failed to process the content
 */
public static <T> T processContent(URL url, IContentProcessor<? extends T> processor) throws IOException {
    String protocol = url.getProtocol();
    if (protocol != null && HTTP_SCHEMES.contains(protocol)) {
        return processHttpContent(url, processor);
    }
    InputStream input;
    try {
        input = url.openStream();
    } catch (IOException e) {
        throw new IOException(MessageFormat.format(Messages.ShafuNetwork_failedToOpenContent, url), e);
    }
    try {
        return processor.process(input);
    } finally {
        input.close();
    }
}

From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java

public static InputStream postConnection(Context context, URL url, String method, String urlParameters)
        throws IOException {
    if (!url.getProtocol().startsWith("http")) {
        return url.openStream();
    }/*from   w  w w .j a  v a  2s.  c  o m*/

    URLConnection c = url.openConnection();

    HttpURLConnection connection = (HttpURLConnection) c;

    connection.setRequestMethod(method.toUpperCase());
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
    connection.setRequestProperty("Content-Language", "en-US");

    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(urlParameters.getBytes("UTF-8"));
        output.flush();
    } finally {
        IOUtils.close(output);
    }
    return connection.getInputStream();
}