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.bstek.dorado.core.pkgs.PackageManager.java

private static void doBuildPackageInfos() throws Exception {
    Map<String, PackageInfo> packageMap = new HashMap<String, PackageInfo>();

    Enumeration<URL> defaultContextFileResources = org.springframework.util.ClassUtils.getDefaultClassLoader()
            .getResources(PACKAGE_PROPERTIES_LOCATION);
    while (defaultContextFileResources.hasMoreElements()) {
        URL url = defaultContextFileResources.nextElement();
        InputStream in = null;//from   w  ww . j a  v a 2s  .co m
        try {
            URLConnection con = url.openConnection();
            con.setUseCaches(false);
            in = con.getInputStream();
            Properties properties = new Properties();
            properties.load(in);

            String packageName = properties.getProperty("name");
            if (StringUtils.isEmpty(packageName)) {
                throw new IllegalArgumentException("Package name undefined.");
            }

            PackageInfo packageInfo = new PackageInfo(packageName);

            packageInfo.setAddonVersion(properties.getProperty("addonVersion"));
            packageInfo.setVersion(properties.getProperty("version"));

            String dependsText = properties.getProperty("depends");
            if (StringUtils.isNotBlank(dependsText)) {
                List<Dependence> dependences = new ArrayList<Dependence>();
                for (String depends : StringUtils.split(dependsText, "; ")) {
                    if (StringUtils.isNotEmpty(depends)) {
                        Dependence dependence = parseDependence(depends);
                        dependences.add(dependence);
                    }
                }
                if (!dependences.isEmpty()) {
                    packageInfo.setDepends(dependences.toArray(new Dependence[0]));
                }
            }

            String license = StringUtils.trim(properties.getProperty("license"));
            if (StringUtils.isNotEmpty(license)) {
                if (INHERITED.equals(license)) {
                    packageInfo.setLicense(LICENSE_INHERITED);
                } else {
                    String[] licenses = StringUtils.split(license);
                    licenses = StringUtils.stripAll(licenses);
                    packageInfo.setLicense(licenses);
                }
            }

            packageInfo.setLoadUnlicensed(BooleanUtils.toBoolean(properties.getProperty("loadUnlicensed")));

            packageInfo.setClassifier(properties.getProperty("classifier"));
            packageInfo.setHomePage(properties.getProperty("homePage"));
            packageInfo.setDescription(properties.getProperty("description"));

            packageInfo.setPropertiesLocations(properties.getProperty("propertiesConfigLocations"));
            packageInfo.setContextLocations(properties.getProperty("contextConfigLocations"));
            packageInfo.setComponentLocations(properties.getProperty("componentConfigLocations"));
            packageInfo.setServletContextLocations(properties.getProperty("servletContextConfigLocations"));

            String configurerClass = properties.getProperty("configurer");
            if (StringUtils.isNotBlank(configurerClass)) {
                Class<?> type = ClassUtils.forName(configurerClass);
                packageInfo.setConfigurer((PackageConfigurer) type.newInstance());
            }

            String listenerClass = properties.getProperty("listener");
            if (StringUtils.isNotBlank(listenerClass)) {
                Class<?> type = ClassUtils.forName(listenerClass);
                packageInfo.setListener((PackageListener) type.newInstance());
            }

            String servletContextListenerClass = properties.getProperty("servletContextListener");
            if (StringUtils.isNotBlank(servletContextListenerClass)) {
                Class<?> type = ClassUtils.forName(servletContextListenerClass);
                packageInfo.setServletContextListener((ServletContextListener) type.newInstance());
            }

            if (packageMap.containsKey(packageName)) {
                PackageInfo conflictPackageInfo = packageMap.get(packageName);
                StringBuffer conflictInfo = new StringBuffer(20);
                conflictInfo.append('[').append(conflictPackageInfo.getName()).append(" - ")
                        .append(conflictPackageInfo.getVersion()).append(']');
                conflictInfo.append(" and ");
                conflictInfo.append('[').append(packageInfo.getName()).append(" - ")
                        .append(packageInfo.getVersion()).append(']');

                Exception e = new IllegalArgumentException("More than one package \"" + packageName
                        + "\" found. They are " + conflictInfo.toString());
                logger.warn(e, e);
            }

            packageMap.put(packageName, packageInfo);
        } catch (Exception e) {
            throw new IllegalArgumentException("Error occured during parsing \"" + url.getPath() + "\".", e);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    List<PackageInfo> calculatedPackages = new ArrayList<PackageInfo>();
    for (PackageInfo packageInfo : packageMap.values()) {
        calculateDepends(packageInfo, calculatedPackages, packageMap);
    }

    packageInfosMap.clear();
    for (PackageInfo packageInfo : calculatedPackages) {
        packageInfosMap.put(packageInfo.getName(), packageInfo);
    }
}

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

public static String getMensajeDesarrollador() {
    String mensaje = null;//from w  w w  .j a  v a 2 s.  c  o m
    try {
        URL url = new URL("http://arasthel.byethost14.com/almeribus/message.html?token="
                + new Random().nextInt(Integer.MAX_VALUE));
        URLConnection connection = url.openConnection();
        connection.setUseCaches(false);
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(15000);
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        mensaje = strBuilder.toString();
    } catch (Exception e) {

    }
    return mensaje;
}

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

public static String getUltimaVersion() {
    String mensaje = null;/*from www .j av a2  s  .c  o  m*/
    try {
        URL url = new URL("http://arasthel.byethost14.com/almeribus/version.html?token="
                + new Random().nextInt(Integer.MAX_VALUE));
        URLConnection connection = url.openConnection();
        connection.setUseCaches(false);
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(15000);
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        mensaje = strBuilder.toString();
    } catch (Exception e) {

    }
    return mensaje;
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static String fetchContent(final URLConnection conn, final int timeout) throws IOException {
    conn.setAllowUserInteraction(true);//from  w  ww. ja  v  a2 s  .c o  m
    if (timeout != 0) {
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
    }
    conn.connect();
    return IOUtils.toString(new InputStreamReader(conn.getInputStream(), UTF8_STR));
}

From source file:hudson.remoting.Launcher.java

private static Document loadDom(URL slaveJnlpURL, URLConnection con)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    return db.parse(con.getInputStream(), slaveJnlpURL.toExternalForm());
}

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

/**
 * Must set {@link #state} to {@link UpdateState#DOWNLOAD_IN_PROGRESS} prior to calling this
 * //from   w w w. j  a va  2s  .  co m
 * @param sender
 * @param isAutomatic
 */
static void download_i(final CommandSender sender, final boolean isAutomatic) {
    assert sender != null;
    stateLock.readLock().lock();
    try {
        if (state != UpdateState.DOWNLOAD_IN_PROGRESS)
            throw new IllegalStateException();
    } finally {
        stateLock.readLock().unlock();
    }
    Skript.info(sender, "" + m_downloading);
    //      boolean hasJar = false;
    //      ZipInputStream zip = null;
    InputStream in = null;
    try {
        final URLConnection conn = new URL(latest.get().downloadURL).openConnection();
        in = conn.getInputStream();
        assert in != null;
        FileUtils.save(in, new File(Bukkit.getUpdateFolderFile(), "Skript.jar"));
        //         zip = new ZipInputStream(conn.getInputStream());
        //         ZipEntry entry;
        ////         boolean hasAliases = false;
        //         while ((entry = zip.getNextEntry()) != null) {
        //            if (entry.getName().endsWith("Skript.jar")) {
        //               assert !hasJar;
        //               save(zip, new File(Bukkit.getUpdateFolderFile(), "Skript.jar"));
        //               hasJar = true;
        //            }// else if (entry.getName().endsWith("aliases.sk")) {
        ////               assert !hasAliases;
        ////               saveZipEntry(zip, new File(Skript.getInstance().getDataFolder(), "aliases-" + latest.get().version + ".sk"));
        ////               hasAliases = true;
        ////            }
        //            zip.closeEntry();
        //            if (hasJar)// && hasAliases)
        //               break;
        //         }
        if (isAutomatic)
            Skript.adminBroadcast("" + m_downloaded);
        else
            Skript.info(sender, "" + m_downloaded);
        stateLock.writeLock().lock();
        try {
            state = UpdateState.DOWNLOADED;
        } finally {
            stateLock.writeLock().unlock();
        }
    } catch (final IOException e) {
        stateLock.writeLock().lock();
        try {
            state = UpdateState.DOWNLOAD_ERROR;
            error.set(ExceptionUtils.toString(e));
            Skript.error(sender, m_download_error.toString());
        } finally {
            stateLock.writeLock().unlock();
        }
    } catch (final Exception e) {
        Skript.exception(e, "Error while downloading the latest version of Skript");
        stateLock.writeLock().lock();
        try {
            state = UpdateState.DOWNLOAD_ERROR;
            error.set(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
        } finally {
            stateLock.writeLock().unlock();
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
            }
        }
    }
}

From source file:org.alfresco.webservice.util.ContentUtils.java

/**
 * Get the content as an imput stream//from ww  w  . jav  a 2 s. c o  m
 * 
 * @param content
 * @return
 */
public static InputStream getContentAsInputStream(Content content) {
    // Get the url and the ticket
    String ticket = AuthenticationUtils.getTicket();
    String strUrl = content.getUrl() + "?ticket=" + ticket;

    try {
        // Create the url connection to the download servlet            
        URL url = new URL(strUrl);
        URLConnection conn = url.openConnection();

        // Set the cookie information
        conn.setRequestProperty("Cookie",
                "JSESSIONID=" + AuthenticationUtils.getAuthenticationDetails().getSessionId() + ";");

        // Return the input stream
        return conn.getInputStream();
    } catch (Exception exception) {
        throw new WebServiceException("Unable to get content as inputStream.", exception);
    }
}

From source file:AnimatedMetadataGraph.java

public static JSONObject getAllResources(URL sfsUrl) {
    if (sfsUrl != null) {
        try {//w ww  . j av  a  2s.  c om
            URL sfsGetRsrcsUrl = new URL(sfsUrl.toString() + "/admin/listrsrcs/");
            URLConnection smapConn = sfsGetRsrcsUrl.openConnection();
            smapConn.setConnectTimeout(5000);
            smapConn.connect();

            //GET reply
            BufferedReader reader = new BufferedReader(new InputStreamReader(smapConn.getInputStream()));
            StringBuffer lineBuffer = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null)
                lineBuffer.append(line);
            line = lineBuffer.toString();
            reader.close();

            return (JSONObject) JSONSerializer.toJSON(line);
        } catch (Exception e) {
            logger.log(Level.WARNING, "", e);
            return null;
        }
    }
    return null;
}

From source file:AnimatedMetadataGraph.java

public static JSONArray getChildren(URL sfsUrl, String path) {
    if (sfsUrl != null) {
        try {// www  .  ja v  a  2  s . co m
            URL sfsGetRsrcsUrl = new URL(sfsUrl.toString() + path);
            URLConnection smapConn = sfsGetRsrcsUrl.openConnection();
            smapConn.setConnectTimeout(5000);
            smapConn.connect();

            //GET reply
            BufferedReader reader = new BufferedReader(new InputStreamReader(smapConn.getInputStream()));
            StringBuffer lineBuffer = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null)
                lineBuffer.append(line);
            line = lineBuffer.toString();
            reader.close();

            JSONObject resp = (JSONObject) JSONSerializer.toJSON(line);
            return resp.optJSONArray("children");
        } catch (Exception e) {
            logger.log(Level.WARNING, "", e);
            return null;
        }
    }
    return null;
}

From source file:com.linkedin.pinot.tools.admin.command.AbstractBaseAdminCommand.java

public static JSONObject postQuery(String query, String brokerBaseApiUrl) throws Exception {
    final JSONObject json = new JSONObject();
    json.put("pql", query);

    final long start = System.currentTimeMillis();
    final URLConnection conn = new URL(brokerBaseApiUrl + "/query").openConnection();
    conn.setDoOutput(true);//from w w  w. j  a  v a 2s.c  o  m
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
    final String reqStr = json.toString();
    System.out.println("reqStr = " + reqStr);

    writer.write(reqStr, 0, reqStr.length());
    writer.flush();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    final long stop = System.currentTimeMillis();

    final String res = sb.toString();
    System.out.println("res = " + res);
    final JSONObject ret = new JSONObject(res);
    ret.put("totalTime", (stop - start));

    return ret;
}