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:io.apiman.servers.gateway_es.Starter.java

/**
 * Loads properties from a file and puts them into system properties.
 *///from ww  w  .  ja v  a2  s . c  om
@SuppressWarnings({ "nls", "unchecked" })
protected static void loadProperties() {
    URL configUrl = Starter.class.getClassLoader().getResource("gateway_es-apiman.properties");
    if (configUrl == null) {
        throw new RuntimeException(
                "Failed to find properties file (see README.md): gateway_es-apiman.properties");
    }
    InputStream is = null;
    try {
        is = configUrl.openStream();
        Properties props = new Properties();
        props.load(is);
        Enumeration<String> names = (Enumeration<String>) props.propertyNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = props.getProperty(name);
            System.setProperty(name, value);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.zack6849.alphabot.api.Utils.java

public static String shortenUrl(String longUrl) {
    String shortened = null;/*from ww w .j a  va2  s . c o  m*/
    try {
        URL url;
        url = new URL("http://is.gd/create.php?format=simple&url=" + longUrl);
        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(url.openStream()));
        shortened = bufferedreader.readLine();
        bufferedreader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return shortened;
}

From source file:de.tudarmstadt.ukp.dkpro.keyphrases.core.evaluator.util.EvaluatorUtils.java

/**
 * Get the gold keyphrases from the file system.
 * By convention gold keyphrase files should have the same name as the document file.
 * Standard extension is .key, but something else can be specified in the corresponding parameter.
 *
 * @param metaData The DocumentMetaData annotation of this document.
 * @param goldSuffix The suffix of the gold standard file.
 * @param toLowerCase If gold keys should be lowercased or not.
 *
 * @return The set of gold keyphrases for this document.
 * @throws AnalysisEngineProcessException an analysis engine process exception
 *//*w  ww . ja  v a2 s  .  c  om*/
public static Set<String> getGoldKeyphrases(DocumentMetaData metaData, String goldSuffix, boolean toLowerCase)
        throws AnalysisEngineProcessException {

    Set<String> goldKeyphrases = new TreeSet<String>();

    String uri = metaData.getDocumentUri();
    URL keyUrl;
    try {
        keyUrl = URI.create(uri.substring(0, indexOfExtension(uri)) + goldSuffix).toURL();

        List<String> lines = IOUtils.readLines(keyUrl.openStream(), "UTF-8");

        for (String line : lines) {
            if (toLowerCase) {
                line = line.toLowerCase().trim();
            } else {
                line = line.trim();
            }
            if (line.length() > 0) {
                if (line.contains(";")) {
                    for (String part : line.split(";")) {
                        goldKeyphrases.add(part.trim());
                    }

                } else {
                    goldKeyphrases.add(line);
                }
            }
        }

        return goldKeyphrases;

    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
}

From source file:io.apiman.gateway.platforms.war.micro.Users.java

public static final List<User> getUsers() throws Exception {
    List<User> rval = new ArrayList<>();

    URL usersUrl = getUsersUrl();

    if (usersUrl != null) {
        System.out.println("Loading users from: " + usersUrl);
        InputStream in = null;/* w ww.ja va 2 s . c  o  m*/
        BufferedReader reader = null;
        try {
            in = usersUrl.openStream();
            reader = new BufferedReader(new InputStreamReader(in));
            String line = reader.readLine();
            while (line != null) {
                line = line.trim();
                if (line.length() == 0 || line.startsWith("#")) {
                    continue;
                }
                String[] split = line.split(",");
                User user = new User();
                user.setId(split[0]);
                user.setPassword(split[1]);
                user.getRoles().add("apipublisher");
                rval.add(user);
                System.out.println("  added user => " + user.getId());
                line = reader.readLine();
            }
        } catch (Throwable t) {
            throw new RuntimeException(t);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(reader);
        }
    } else {
        System.out.println("Using default users.");
        User user = new User();
        user.setId("admin");
        user.setPassword("admin123!");
        user.getRoles().add("apiuser");
        user.getRoles().add("apiadmin");
        rval.add(user);
    }

    return rval;
}

From source file:Main.java

public static String getDefaultNamespaceUri(URL xmlResource, String rootElementName)
        throws IOException, ParserConfigurationException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);// ww  w . j  a va 2 s. c  om
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(xmlResource.openStream());
    NodeList nodes = document.getElementsByTagName(rootElementName);
    if (nodes == null || nodes.getLength() == 0) {
        throw new IllegalArgumentException("Root element \"" + rootElementName + "\" not found in xml \""
                + xmlResource.toExternalForm() + "\".");
    }
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Node xmlns = node.getAttributes().getNamedItem("xmlns");
        if (xmlns != null) {
            String value = xmlns.getNodeValue();
            return value.substring(value.indexOf("=") + 1);
        }
    }
    return null;
}

From source file:bammerbom.ultimatecore.bukkit.commands.CmdMinecraftservers.java

public static Status getStatus(MinecraftServer service) {
    String status;/*from  w ww. j  av  a2s .c  o  m*/

    try {
        URL url = new URL("http://status.mojang.com/check?service=" + service.getURL());
        BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
        Object object = parser.parse(input);
        JSONObject jsonObject = (JSONObject) object;

        status = (String) jsonObject.get(service.getURL());
    } catch (Exception e) {
        return Status.UNKNOWN;
    }

    return status(status);
}

From source file:io.fabric8.insight.log.support.LogQuerySupport.java

protected static String loadString(URL url) throws IOException {
    InputStream is = url.openStream();
    if (is == null) {
        return null;
    }/*from ww  w  .  j a v  a  2 s  . com*/
    try {
        InputStreamReader reader = new InputStreamReader(is);
        StringWriter writer = new StringWriter();
        final char[] buffer = new char[4096];
        int n;
        while (-1 != (n = reader.read(buffer))) {
            writer.write(buffer, 0, n);
        }
        writer.flush();
        return writer.toString();
    } finally {
        is.close();
    }
}

From source file:com.taobao.android.builder.tools.ideaplugin.ApDownloader.java

public static File downloadAP(String mtlConfigUrl, File root) throws Exception {

    Pattern p = Pattern.compile("buildConfigId=(\\d+)");
    Matcher m = p.matcher(mtlConfigUrl);

    String configId = "";

    if (m.find()) {
        configId = m.group(1);/*from  ww  w.jav  a2s  .c  om*/
    }

    String apiUrl = "http://" + AtlasBuildContext.sBuilderAdapter.tpatchHistoryUrl
            + "/rpc/androidPlugin/getAp.json?buildConfigId=" + configId;

    URL api = new URL(apiUrl);
    BufferedReader in = new BufferedReader(new InputStreamReader(api.openStream()));

    String inputLine = in.readLine();
    in.close();

    String downloadUrl = inputLine.trim().replace("\"", "").replace("\\", "");

    File file = new File(root, MD5Util.getMD5(downloadUrl) + ".ap");
    if (file.exists()) {
        return file;
    }

    URL downloadApi = new URL(downloadUrl);
    System.out.println("start to download ap from " + downloadUrl);

    File tmpFile = new File(file.getParentFile(), String.valueOf(System.currentTimeMillis()));

    FileUtils.copyURLToFile(downloadApi, file);
    return file;

}

From source file:launcher.workflow.update.UpdateWorkflow.java

public static void begin(final Settings launcherCfg, final String license) {
    WorkflowStep prepare = new WorkflowStep("Preparing to launch the game", new WorkflowAction() {
        @Override/*  w w w.ja  v  a  2  s  .  com*/
        public boolean act() {
            return true;
        }
    });
    WorkflowStep checkLicense = new WorkflowStep("Checking to see if a license has been entered.",
            new WorkflowAction() {
                @Override
                public boolean act() throws Exception {
                    if (license == null || license.isEmpty()) {
                        LaunchLogger.error(LaunchLogger.Tab + "No valid license found.");
                        return false;
                    }

                    WorkflowWindowManager.setProgressVisible(true);
                    URL licenseCheckUrl = new URL(launcherCfg.licenseCall(license));
                    String response = IOUtils.toString(licenseCheckUrl.openStream());
                    WorkflowWindowManager.setProgressVisible(false);
                    if (response.contains("true")) {
                        LaunchLogger.info(LaunchLogger.Tab + "License is valid.");
                        return true;
                    } else {
                        if (License.isCached()) {
                            LaunchLogger
                                    .info("Invalid license was found. Deleting the locally cached license.");
                            License.deleteCache();
                            return false;
                        }
                    }
                    return false;
                }
            });

    WorkflowStep checkVersion = new WorkflowStep("Checking for updates.", new WorkflowAction() {
        @Override
        public boolean act() throws Exception {
            File versionPath = new File("assets/data/version.dat");
            String myVersion = "0.0.0";
            if (versionPath.exists()) {
                myVersion = FileUtils.readFileToString(versionPath);
                LaunchLogger.info("Detected version: " + myVersion);
            }
            WorkflowWindowManager.setProgressVisible(true);
            URL versionCheckUrl = new URL(launcherCfg.versionCall(myVersion));

            String result = IOUtils.toString(versionCheckUrl.openStream());
            WorkflowWindowManager.setProgressVisible(false);
            if (result.contains("true")) {
                LaunchLogger.info(LaunchLogger.Tab + "Local copy of the game is out of date.");
                return true;
            }
            LaunchLogger.info(LaunchLogger.Tab + "Local copy of the game is up to date. No update required.");
            return false;
        }
    });

    WorkflowStep downloadUpdate = new WorkflowStep("Preparing the update location", new WorkflowAction() {
        @Override
        public boolean act() throws Exception {
            if (UpdateWorkflowData.UpdateArchive.exists()) {
                FileUtils.forceDelete(UpdateWorkflowData.UpdateArchive);
            }

            int responseTimeoutMs = launcherCfg.responseTimeoutMilliseconds;
            int downloadTimeoutMs = launcherCfg.downloadTimeoutMilliseconds;
            LaunchLogger.info("Attempting to download an update using license: [" + license + "]");

            WorkflowWindowManager.setProgressVisible(true);
            String downloadUrl = launcherCfg.downloadCall(license, "update");
            LaunchLogger.info("Downloading latest stable edition");
            FileUtils.copyURLToFile(new URL(downloadUrl), UpdateWorkflowData.UpdateArchive, responseTimeoutMs,
                    downloadTimeoutMs);
            WorkflowWindowManager.setProgressVisible(false);

            LaunchLogger.info(LaunchLogger.Tab + "Update downloaded successfully.");
            return true;
        }
    });

    WorkflowStep applyUpdate = new WorkflowStep("Unpacking update archive", new WorkflowAction() {
        @Override
        public boolean act() throws IOException {
            WorkflowWindowManager.setProgressVisible(true);
            Archive.unzip(UpdateWorkflowData.UpdateArchive, UpdateWorkflowData.UpdateWorkingDirectory);
            LaunchLogger.info("Replacing old content");
            File game = new File(UpdateWorkflowData.UpdateWorkingDirectory + "/game.jar");
            File gameTarget = new File("./");
            LaunchLogger.info("Attempting to copy: " + game + " to " + gameTarget);
            FileUtils.copyFileToDirectory(game, gameTarget);

            File assets = new File(UpdateWorkflowData.UpdateWorkingDirectory + "/assets");
            File assetsTarget = new File("./assets");
            LaunchLogger.info("Attempting to copy: " + assets + " to " + assetsTarget);
            FileUtils.copyDirectory(assets, assetsTarget);
            WorkflowWindowManager.setProgressVisible(false);

            LaunchLogger.info(LaunchLogger.Tab + "Update applied successfully.");
            return true;
        }
    });

    WorkflowStep clean = new WorkflowStep("Cleaning up temporary files", new WorkflowAction() {
        @Override
        public boolean act() throws IOException {
            if (UpdateWorkflowData.UpdateArchive.exists()) {
                FileUtils.forceDelete(UpdateWorkflowData.UpdateArchive);
            }
            if (UpdateWorkflowData.UpdateWorkingDirectory.exists()) {
                FileUtils.deleteDirectory(UpdateWorkflowData.UpdateWorkingDirectory);
            }
            return true;
        }
    });

    prepare.setOnSuccess(checkLicense);
    checkLicense.setOnSuccess(checkVersion);
    checkVersion.setOnSuccess(downloadUpdate);
    downloadUpdate.setOnSuccess(applyUpdate);
    applyUpdate.setOnSuccess(clean);

    prepare.setOnFailure(clean);
    checkLicense.setOnFailure(clean);
    checkVersion.setOnFailure(clean);
    downloadUpdate.setOnFailure(clean);
    applyUpdate.setOnFailure(clean);

    prepare.execute();
}

From source file:io.apiman.manager.api.micro.Users.java

public static final List<User> getUsers() throws Exception {
    List<User> rval = new ArrayList<>();

    URL usersUrl = getUsersUrl();

    if (usersUrl != null) {
        System.out.println("Loading users from: " + usersUrl);
        InputStream in = null;/*from  w  ww .j  a v a  2s.co m*/
        BufferedReader reader = null;
        try {
            in = usersUrl.openStream();
            reader = new BufferedReader(new InputStreamReader(in));
            String line = reader.readLine();
            while (line != null) {
                line = line.trim();
                if (line.length() == 0 || line.startsWith("#")) {
                    continue;
                }
                String[] split = line.split(",");
                User user = new User();
                user.setId(split[0]);
                user.setPassword(split[1]);
                user.getRoles().add("apiuser");
                boolean isAdmin = "true".equals(split[2]);
                if (isAdmin) {
                    user.getRoles().add("apiadmin");
                }
                rval.add(user);
                System.out.println("  added user => " + user.getId());
                line = reader.readLine();
            }
        } catch (Throwable t) {
            throw new RuntimeException(t);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(reader);
        }
    } else {
        System.out.println("Using default users.");
        User user = new User();
        user.setId("admin");
        user.setPassword("admin123!");
        user.getRoles().add("apiuser");
        user.getRoles().add("apiadmin");
        rval.add(user);
    }

    return rval;
}