Example usage for java.net URLConnection getInputStream

List of usage examples for java.net URLConnection getInputStream

Introduction

In this page you can find the example usage for java.net URLConnection getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:com.pa165.ddtroops.console.client.Application.java

/**
 * Print list of all roles/*from  ww  w  .j a va  2s . c o m*/
 */
private static void getAllRoles() {
    try {
        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String s = "";
        List<RoleDTO> role = new ArrayList<RoleDTO>();
        while ((s = in.readLine()) != null) {
            role = mapper.readValue(s, new TypeReference<List<RoleDTO>>() {
            });
        }
        System.out.println("All roles");
        for (RoleDTO r : role) {
            System.out.println("ID: " + r.getId() + ", NAME: " + r.getName() + ", DESCRIPTION: "
                    + r.getDescription() + ", ENERGY: " + r.getEnergy() + ", ATTACK: " + r.getAttack()
                    + ", DEFENSE: " + r.getDefense());
        }
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when returning all roles");
        System.out.println(e);
    }
}

From source file:de.schildbach.wallet.marscoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getmarscoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;/*from ww  w.jav a2  s . c o m*/
    try {
        String currencies[] = { "BTC" };
        //String urls[] = {"https://cryptorush.in/api.php?get=market&m=mrs&b=btc&json=true"};
        String urls[] = { "http://hlds.ws/marscoinj/api" };
        for (int i = 0; i < currencies.length; ++i) {
            final String currencyCode = currencies[i];
            final URL URL = new URL(urls[i]);
            final URLConnection connection = URL.openConnection();
            connection.setConnectTimeout(TIMEOUT_MS);
            connection.setReadTimeout(TIMEOUT_MS);
            connection.connect();
            final StringBuilder content = new StringBuilder();

            Reader reader = null;
            try {
                reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
                IOUtils.copy(reader, content);
                final JSONObject head = new JSONObject(content.toString());
                //JSONObject ticker = head.getJSONObject("ticker");
                //rate = Float.parseFloat(head.getString("current_ask"));
                Double avg = head.getDouble("current_ask");
                //Double avg = Float.parseFloat(head.getString("current_ask"));
                String euros = String.format("%.8f", avg);
                // Fix things like 3,1250
                euros = euros.replace(",", ".");
                rates.put(currencyCode,
                        new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost()));
                if (currencyCode.equalsIgnoreCase("BTC"))
                    btcRate = avg;
            } finally {
                if (reader != null)
                    reader.close();
            }
        }
        // Handle LTC/EUR special since we have to do maths
        final URL URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in euros.  We want MRS!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:ec.edu.ucuenca.dcc.sld.HttpUtils.java

public static synchronized String Http(String s) throws SQLException, IOException {

    String resp = "";
    final URL url = new URL(s);
    final URLConnection connection = url.openConnection();
    connection.setConnectTimeout(60000);
    connection.setReadTimeout(60000);/*from  www  .  ja va  2 s .c o  m*/
    connection.addRequestProperty("User-Agent",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0");
    connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8");
    while (reader.hasNextLine()) {
        final String line = reader.nextLine();
        resp += line + "\n";
    }
    reader.close();

    return resp;
}

From source file:resources.XmlToAnime.java

private static InputStream getInput() {
    String username = "shigato";
    String password = "unlimited0";
    String authString = username + ":" + password;
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    InputStream in = null;//w ww .j  a  va2s  .c o  m

    try {
        URL url = new URL(sUrl);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        urlConnection.setRequestProperty("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        urlConnection.setRequestProperty("Accept-Language", "en");
        urlConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36");
        in = urlConnection.getInputStream();
        String temp = InputStreamToString.getStringFromInputStream(in);
        temp = Replacer.replaceIllegalCharacters(temp);
        in = new ByteArrayInputStream(temp.getBytes(StandardCharsets.UTF_8));
        System.out.println();

        //            InputStreamReader isr = new InputStreamReader(in);
        //            
        //            int numCharsRead;
        //            char[] charArray = new char[1024];
        //            StringBuilder sb = new StringBuilder();
        //            while ((numCharsRead = isr.read(charArray)) > 0) {
        //                    sb.append(charArray, 0, numCharsRead);
        //            }
        //            String result = sb.toString();
        //            System.out.println(result);

    } catch (IOException e) {

    }
    return in;
}

From source file:sce.RESTAppMetricJob.java

public static ByteBuffer getAsByteArray(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    ByteArrayOutputStream tmpOut;
    try (InputStream in = connection.getInputStream()) {
        int contentLength = connection.getContentLength();
        if (contentLength != -1) {
            tmpOut = new ByteArrayOutputStream(contentLength);
        } else {//from  w  w w  .  j  a  va 2s  . c o m
            tmpOut = new ByteArrayOutputStream(16384); // pick some appropriate size
        }
        byte[] buf = new byte[512];
        while (true) {
            int len = in.read(buf);
            if (len == -1) {
                break;
            }
            tmpOut.write(buf, 0, len);
        }
    }
    tmpOut.close();
    byte[] array = tmpOut.toByteArray();
    return ByteBuffer.wrap(array);
}

From source file:mas.MAS_TOP_PAPERS.java

/**
 * @param args the command line arguments
 *///  w  w  w.j av  a  2  s . c o m
// for old version
public static void getData(int startIdx, int endIdx) {
    try {
        Properties prop = new Properties();
        prop.setProperty("AppId", "1df63064-efad-4bbd-a797-1131499b7728");
        prop.setProperty("ResultObjects", "publication");
        prop.setProperty("DomainID", "22");
        prop.setProperty("SubDomainID", "2");
        prop.setProperty("YearStart", "2001");
        prop.setProperty("YearEnd", "2010");
        prop.setProperty("StartIdx", startIdx + "");
        prop.setProperty("EndIdx", endIdx + "");

        String url_org = "http://academic.research.microsoft.com/json.svc/search";
        String url_str = generateURL(url_org, prop);
        URL url = new URL(url_str);
        URLConnection yc = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
        }
        in.close();
    } catch (MalformedURLException ex) {
        Logger.getLogger(MAS_TOP_PAPERS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MAS_TOP_PAPERS.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ch.njol.skript.Updater.java

/**
 * @param sender Sender to receive messages
 * @param download Whether to directly download the newest version if one is found
 * @param isAutomatic/*from w  ww. ja  v  a 2  s. co m*/
 */
static void check(final CommandSender sender, final boolean download, final boolean isAutomatic) {
    stateLock.writeLock().lock();
    try {
        if (state == UpdateState.CHECK_IN_PROGRESS || state == UpdateState.DOWNLOAD_IN_PROGRESS)
            return;
        state = UpdateState.CHECK_IN_PROGRESS;
    } finally {
        stateLock.writeLock().unlock();
    }
    if (!isAutomatic || Skript.logNormal())
        Skript.info(sender, "" + m_checking);
    Skript.newThread(new Runnable() {
        @Override
        public void run() {
            infos.clear();

            InputStream in = null;
            try {
                final URLConnection conn = new URL(filesURL).openConnection();
                conn.setRequestProperty("User-Agent", "Skript/v" + Skript.getVersion() + " (by Njol)");
                in = conn.getInputStream();
                final BufferedReader reader = new BufferedReader(new InputStreamReader(in,
                        conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding()));
                try {
                    final String line = reader.readLine();
                    if (line != null) {
                        final JSONArray a = (JSONArray) JSONValue.parse(line);
                        for (final Object o : a) {
                            final Object name = ((JSONObject) o).get("name");
                            if (!(name instanceof String)
                                    || !((String) name).matches("\\d+\\.\\d+(\\.\\d+)?( \\(jar( only)?\\))?"))// not the default version pattern to not match beta/etc. versions
                                continue;
                            final Object url = ((JSONObject) o).get("downloadUrl");
                            if (!(url instanceof String))
                                continue;

                            final Version version = new Version(((String) name).contains(" ")
                                    ? "" + ((String) name).substring(0, ((String) name).indexOf(' '))
                                    : ((String) name));
                            if (version.compareTo(Skript.getVersion()) > 0) {
                                infos.add(new VersionInfo((String) name, version, (String) url));
                            }
                        }
                    }
                } finally {
                    reader.close();
                }

                if (!infos.isEmpty()) {
                    Collections.sort(infos);
                    latest.set(infos.get(0));
                } else {
                    latest.set(null);
                }

                getChangelogs(sender);

                final String message = infos.isEmpty()
                        ? (Skript.getVersion().isStable() ? "" + m_running_latest_version
                                : "" + m_running_latest_version_beta)
                        : "" + m_update_available;
                if (isAutomatic && !infos.isEmpty()) {
                    Skript.adminBroadcast(message);
                } else {
                    Skript.info(sender, message);
                }

                if (download && !infos.isEmpty()) {
                    stateLock.writeLock().lock();
                    try {
                        state = UpdateState.DOWNLOAD_IN_PROGRESS;
                    } finally {
                        stateLock.writeLock().unlock();
                    }
                    download_i(sender, isAutomatic);
                } else {
                    stateLock.writeLock().lock();
                    try {
                        state = UpdateState.CHECKED_FOR_UPDATE;
                    } finally {
                        stateLock.writeLock().unlock();
                    }
                }
            } catch (final IOException e) {
                stateLock.writeLock().lock();
                try {
                    state = UpdateState.CHECK_ERROR;
                    error.set(ExceptionUtils.toString(e));
                    if (sender != null)
                        Skript.error(sender, m_check_error.toString());
                } finally {
                    stateLock.writeLock().unlock();
                }
            } catch (final Exception e) {
                if (sender != null)
                    Skript.error(sender, m_internal_error.toString());
                Skript.exception(e, "Unexpected error while checking for a new version of Skript");
                stateLock.writeLock().lock();
                try {
                    state = UpdateState.CHECK_ERROR;
                    error.set(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
                } finally {
                    stateLock.writeLock().unlock();
                }
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (final IOException e) {
                    }
                }
            }
        }
    }, "Skript update thread").start();
}

From source file:gate.DocumentFormat.java

/**
  * Returns a MymeType having as input a URL object. If the MimeType wasn't
  * recognized it returns <b>null</b>.
  * @param url The URL object from which the MimeType will be extracted
  * @return A MimeType object for that URL, or <b>null</b> if the Mime Type is
  * unknown.//www  . ja va2  s.c  o m
  */
static private MimeType getMimeType(URL url) {
    String mimeTypeString = null;
    String charsetFromWebServer = null;
    String contentType = null;
    InputStream is = null;
    MimeType mimeTypeFromWebServer = null;
    MimeType mimeTypeFromFileSuffix = null;
    MimeType mimeTypeFromMagicNumbers = null;

    if (url == null)
        return null;
    // Ask the web server for the content type
    // We expect to get contentType something like this:
    // "text/html; charset=iso-8859-1"
    // Charset is optional

    try {
        try {
            URLConnection urlconn = url.openConnection();
            is = urlconn.getInputStream();
            contentType = urlconn.getContentType();
        } catch (IOException e) {
            // Failed to get the content type with te Web server.
            // Let's try some other methods like FileSuffix or magic numbers.
        }
        // If a content Type was returned by the server, try to get the mime Type
        // string
        // If contentType is something like this:"text/html; charset=iso-8859-1"
        // try to get content Type string (text/html)
        if (contentType != null) {
            StringTokenizer st = new StringTokenizer(contentType, ";");
            // We assume that the first token is the mime type string...
            // If this doesn't happen then BAD LUCK :(( ...
            if (st.hasMoreTokens())
                mimeTypeString = st.nextToken().toLowerCase();
            // The next token it should be the CharSet
            if (st.hasMoreTokens())
                charsetFromWebServer = st.nextToken().toLowerCase();
            if (charsetFromWebServer != null) {
                //We have something like : "charset=iso-8859-1" and let's extract the
                // encoding.
                st = new StringTokenizer(charsetFromWebServer, "=");
                // Don't need this anymore
                charsetFromWebServer = null;
                // Discarding the first token which is : "charset"
                if (st.hasMoreTokens())
                    st.nextToken();
                // Get the encoding : "ISO-8859-1"
                if (st.hasMoreTokens())
                    charsetFromWebServer = st.nextToken().toUpperCase();
            } // End if
        } // end if
          // Return the corresponding MimeType with WebServer from the associated MAP
        mimeTypeFromWebServer = mimeString2mimeTypeMap.get(mimeTypeString);
        // Let's try a file suffix detection
        // mimeTypeFromFileSuffix = getMimeType(getFileSuffix(url));    
        for (String suffix : getFileSuffixes(url)) {
            mimeTypeFromFileSuffix = getMimeType(suffix);
            if (mimeTypeFromFileSuffix != null)
                break;
        }

        // Let's perform a magic numbers guess..
        mimeTypeFromMagicNumbers = guessTypeUsingMagicNumbers(is, charsetFromWebServer);
    } finally {
        IOUtils.closeQuietly(is); //null safe
    }
    //All those types enter into a deciding system
    return decideBetweenThreeMimeTypes(mimeTypeFromWebServer, mimeTypeFromFileSuffix, mimeTypeFromMagicNumbers);
}

From source file:jeeves.xlink.Processor.java

/**
 * Resolves an xlink/*from  w ww  .  ja v a2s .  c o  m*/
 */
public static synchronized Element resolveXLink(String uri, String idSearch, ServiceContext srvContext)
        throws IOException, JDOMException, CacheException {

    cleanFailures();
    if (failures.size() > MAX_FAILURES) {
        throw new RuntimeException("There have been " + failures.size()
                + " timeouts resolving xlinks in the last " + ELAPSE_TIME + " ms");
    }
    Element remoteFragment = null;
    try {
        // TODO-API: Support local protocol on /api/registries/
        if (uri.startsWith(XLink.LOCAL_PROTOCOL)) {
            SpringLocalServiceInvoker springLocalServiceInvoker = srvContext
                    .getBean(SpringLocalServiceInvoker.class);
            remoteFragment = (Element) springLocalServiceInvoker.invoke(uri);
        } else {
            // Avoid references to filesystem
            if (uri.toLowerCase().startsWith("file://")) {
                return null;
            }

            uri = uri.replaceAll("&+", "&");
            String mappedURI = mapURI(uri);

            JeevesJCS xlinkCache = JeevesJCS.getInstance(XLINK_JCS);
            remoteFragment = (Element) xlinkCache.getFromGroup(uri.toLowerCase(), mappedURI);
            if (remoteFragment == null) {
                Log.info(Log.XLINK_PROCESSOR, "cache MISS on " + uri.toLowerCase());
                URL url = new URL(uri.replaceAll("&amp;", "&"));

                URLConnection conn = url.openConnection();
                conn.setConnectTimeout(1000);

                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
                try {
                    remoteFragment = Xml.loadStream(in);
                    if (Log.isDebugEnabled(Log.XLINK_PROCESSOR))
                        Log.debug(Log.XLINK_PROCESSOR, "Read:\n" + Xml.getString(remoteFragment));
                } finally {
                    in.close();
                }
            } else {
                Log.debug(Log.XLINK_PROCESSOR, "cache HIT on " + uri.toLowerCase());
            }

            if (remoteFragment != null && !remoteFragment.getName().equalsIgnoreCase("error")) {
                xlinkCache.putInGroup(uri.toLowerCase(), mappedURI, remoteFragment);
                if (Log.isDebugEnabled(Log.XLINK_PROCESSOR))
                    Log.debug(Log.XLINK_PROCESSOR, "cache miss for " + uri);
            } else {
                return null;
            }

        }
    } catch (Exception e) { // MalformedURLException, IOException
        synchronized (Processor.class) {
            failures.add(System.currentTimeMillis());
        }

        Log.error(Log.XLINK_PROCESSOR, "Failed on " + uri, e);
    }

    // search for and return only the xml fragment that has @id=idSearch

    Element res = null;
    if (idSearch != null) {
        String xpath = "*//*[@id='" + idSearch + "']";
        try {
            res = Xml.selectElement(remoteFragment, xpath);
            if (res != null) {
                res = (Element) res.clone();
                res.removeAttribute("id");
            }
        } catch (Exception e) {
            Log.warning(Log.XLINK_PROCESSOR,
                    "Failed to search for remote fragment using " + xpath + ", error" + e.getMessage());
            return null;
        }
    } else {
        if (remoteFragment == null) {
            return null;
        } else {
            res = (Element) remoteFragment.clone();
        }
    }
    if (Log.isDebugEnabled(Log.XLINK_PROCESSOR))
        Log.debug(Log.XLINK_PROCESSOR, "Read:" + Xml.getString(res));
    return res;
}

From source file:Main.java

/**
 *  This method is used to send a XML request file to web server to process the request and return
 *  xml response containing event id.//  w  w w.j av a  2  s .  c  om
 */
public static String postXMLWithTimeout(String postUrl, String xml, int readTimeout) throws Exception {

    System.out.println("XMLUtils.postXMLWithTimeout: Connecting to Web Server .......");

    InputStream in = null;
    BufferedReader bufferedReader = null;
    OutputStream out = null;
    PrintWriter printWriter = null;
    StringBuffer responseMessageBuffer = new StringBuffer("");

    try {
        URL url = new URL(postUrl);
        URLConnection con = url.openConnection();

        // Prepare for both input and output
        con.setDoInput(true);
        con.setDoOutput(true);

        // Turn off caching
        con.setUseCaches(false);
        con.setRequestProperty("Content-Type", "text/xml");
        con.setReadTimeout(readTimeout);
        out = con.getOutputStream();
        // Write the arguments as post data
        printWriter = new PrintWriter(out);

        printWriter.println(xml);
        printWriter.flush();

        //Process response and return back to caller function
        in = con.getInputStream();
        bufferedReader = new BufferedReader(new InputStreamReader(in));
        String tempStr = null;

        int tempClearResponseMessageBufferCounter = 0;
        while ((tempStr = bufferedReader.readLine()) != null) {
            tempClearResponseMessageBufferCounter++;
            //clear the buffer for the first time
            if (tempClearResponseMessageBufferCounter == 1)
                responseMessageBuffer.setLength(0);
            responseMessageBuffer.append(tempStr);
        }

    } catch (Exception ex) {
        throw ex;
    } finally {
        System.out.println("Calling finally in POSTXML");
        try {
            if (in != null)
                in.close();
        } catch (Exception eex) {
            System.out.println("COULD NOT Close Input Stream in try");
        }
        try {
            if (out != null)
                out.close();
        } catch (Exception eex) {
            System.out.println("COULD NOT Close Output Stream in try");
        }

    }
    System.out.println("XMLUtils.postXMLWithTimeout: end .......");
    return responseMessageBuffer.toString();
}