Example usage for java.net URI toURL

List of usage examples for java.net URI toURL

Introduction

In this page you can find the example usage for java.net URI toURL.

Prototype

public URL toURL() throws MalformedURLException 

Source Link

Document

Constructs a URL from this URI.

Usage

From source file:org.jboss.pnc.termdbuilddriver.transfer.TermdFileTranser.java

public StringBuffer downloadFileToStringBuilder(StringBuffer logsAggregate, URI uri) throws TransferException {
    try {/*from  ww w .j  av  a 2s  .  c o  m*/
        logger.debug("Downloading file to String Buffer from {}", uri);

        StringWriter writer = new StringWriter();
        HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
        connection.setRequestMethod("GET");

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

        try (InputStream inputStream = connection.getInputStream()) {
            IOUtils.copy(inputStream, writer, ENCODING);
        }

        logsAggregate.append("==== ").append(uri.toString()).append(" ====\n");
        logsAggregate.append(writer.getBuffer());

        logger.trace("Downloaded {}", writer.getBuffer().toString());
        return logsAggregate;
    } catch (IOException e) {
        throw new TransferException("Could not obtain log file: " + uri.toString(), e);
    }
}

From source file:gmusic.api.comm.ApacheConnector.java

private HttpRequestBase adjustAddress(URI address, HttpRequestBase request)
        throws MalformedURLException, URISyntaxException {
    if (address.toString().startsWith(HTTPS_PLAY_GOOGLE_COM_MUSIC_SERVICES)) {
        address = new URI(address.toURL() + String.format(COOKIE_FORMAT, getCookieValue("xt")));
    }// www .j  a va 2s .  c  o m

    request.setURI(address);

    if (authorizationToken != null) {
        request.addHeader(GOOGLE_LOGIN_AUTH_KEY, String.format(GOOGLE_LOGIN_AUTH_VALUE, authorizationToken));
    }
    // if((address.toString().startsWith("https://android.clients.google.com/music/mplay")) && deviceId != null)
    // {
    // request.addHeader("X-Device-ID", deviceId);
    // }

    return request;
}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderPropertiesFileLoginModule.java

public void loadProperties(ServerInfo serverInfo, URI groupURI) throws GeronimoSecurityException {
    try {//from w w  w .j  a  va  2 s  .  c  o m
        URI groupFile = serverInfo.resolveServer(groupURI);
        Properties temp = new Properties();
        InputStream stream = groupFile.toURL().openStream();
        temp.load(stream);
        stream.close();

        Enumeration e = temp.keys();
        while (e.hasMoreElements()) {
            String groupName = (String) e.nextElement();
            String[] userList = ((String) temp.get(groupName)).split(",");

            Set<String> userset = roleUsersMap.get(groupName);
            if (userset == null) {
                userset = new HashSet<String>();
                roleUsersMap.put(groupName, userset);
            }
            for (String user : userList) {
                userset.add(user);
            }
        }

    } catch (Exception e) {
        log.error("Generic HTTP Header Properties File Login Module - data load failed", e);
        throw new GeronimoSecurityException(e);
    }
}

From source file:iristk.cfg.ABNFGrammar.java

public ABNFGrammar(URI uri) throws IOException, GrammarException {
    this.uri = uri;
    readInputStream(uri.toURL().openStream());
}

From source file:com.janoz.usenet.searchers.impl.NzbsOrgConnectorImpl.java

public void validate() throws SearchException {
    THROTTLER.throttle();//from   w w  w. j  a  va  2s . c o  m
    InputStreamReader isr = null;
    try {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("action", "getnzb"));
        params.add(new BasicNameValuePair("nzbid", "" + 0));
        URI uri = getUri("index.php", params);
        isr = new InputStreamReader((InputStream) uri.toURL().getContent());

        char[] buffer = new char[BUFFSIZE];
        int numRead;
        int trueCount = 0;
        int falseCount = 0;
        while ((numRead = isr.read(buffer)) > 0) {
            for (int c = 0; c < numRead; c++) {
                if (buffer[c] == VALID_STRING.charAt(trueCount)) {
                    trueCount++;
                } else {
                    trueCount = 0;
                }
                if (trueCount == VALID_STRING.length())
                    return;
                if (buffer[c] == INVALID_STRING.charAt(falseCount)) {
                    falseCount++;
                } else {
                    falseCount = 0;
                }
                if (falseCount == INVALID_STRING.length()) {
                    throw new SearchException("Invalid credentials.");
                }
            }
        }
        throw new SearchException("Unable to determine validity.");
    } catch (IOException ioe) {
        throw new SearchException("Error connecting to Nzbs.org.", ioe);
    } catch (URISyntaxException e) {
        throw new SearchException("Error parsing URI.", e);
    } finally {
        THROTTLER.setThrottleForNextAction();
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException e) {
                /* dan niet */
            }
        }
    }
}

From source file:org.rifidi.edge.init.Activator.java

@Override
public void start(BundleContext arg0) throws Exception {

    try {/*from  w w w .j a  v a 2s.  co m*/
        System.out.println("START RIFIDI INITIALIZTION BUNDLE");

        boolean failoverEnabled = false;
        String primary = System.getProperty("org.rifidi.failover.primary");
        if (primary != null && !primary.equals("")) {
            failoverEnabled = true;
        }
        if (failoverEnabled) {
            System.out.println("Primary: " + primary);
            Integer failoverTrySeconds = Integer.parseInt(System.getProperty("org.rifidi.failover.frequency"));
            Integer numFailsRequired = Integer.parseInt(System.getProperty("org.rifidi.failover.failurecount"));
            for (int numFails = 0; numFails < numFailsRequired;) {
                CloseableHttpClient httpclient = null;
                try {
                    Thread.sleep(failoverTrySeconds * 1000);
                    httpclient = HttpClients.createDefault();
                    int CONNECTION_TIMEOUT_MS = 5 * 1000; // Timeout in millis.
                    RequestConfig requestConfig = RequestConfig.custom()
                            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
                            .setConnectTimeout(CONNECTION_TIMEOUT_MS).setSocketTimeout(CONNECTION_TIMEOUT_MS)
                            .build();

                    HttpGet httpGet = new HttpGet("http://" + primary + "/ping");
                    httpGet.setConfig(requestConfig);
                    httpclient.execute(httpGet);

                    System.out.println("Response received from " + primary + ", sleeping for "
                            + failoverTrySeconds + " seconds");
                    // Got past the get()...reset the counter
                    if (numFails > 0) {
                        System.out.println("Request to primary " + primary
                                + " succeeded after previous failure, resetting the counter");
                        numFails = 0;
                    }
                } catch (InterruptedException e) {
                    System.out.println("Interrupted Exception -- trying again");
                    // Do nothing...wasn't a network failure
                } catch (Exception e) {
                    // Exception happened, could not connect to
                    numFails++;
                    System.out.println("Failed to connect to primary " + primary + ", incrementing counter: "
                            + numFails + " number of fails required: " + numFailsRequired);
                } finally {
                    if (httpclient != null) {
                        httpclient.close();
                    }
                }
            }

            // TODO: Call the primary here, get a response.
        }

        // look up the path to the rifidi home directory
        String rifidiHome = System.getProperty("org.rifidi.home");

        // if it's null, set it to the "user.dir" directory
        if (rifidiHome == null) {
            String userDir = System.getProperty("user.dir");
            System.setProperty("org.rifidi.home", userDir);
            rifidiHome = System.getProperty("org.rifidi.home");
        }
        System.out.println(
                "ALL RIFIDI CONFIGURATION PATHS RELATIVE TO : " + System.getProperty("org.rifidi.home"));

        // set the path to the applications folder
        System.setProperty("org.rifidi.edge.applications", "applications");

        // set up logging
        String slash = "";
        if (rifidiHome.charAt(0) != '/') {
            slash = "/";
        }
        String s = "file:" + slash + rifidiHome + System.getProperty("file.separator")
                + System.getProperty("org.rifidi.edge.logging");
        // We have to do this bit of idiocy to get URIs to work with windows
        // backslashes and "Documents and Settings".
        URI uri = new URI(URIUtility.createURI(s));

        if (new File(uri).exists()) {
            PropertyConfigurator.configure(uri.toURL());
            System.out.println("Using log4j configuration at: " + s);
        } else {
            System.out.println("Cannot find log properties file at " + s + " Using default log4j properties");
            PropertyConfigurator.configure(getClass().getResource("/log4j.properties"));
        }

        System.setProperty("activemq.base", rifidiHome + File.separator + "config");
    } catch (Throwable e) {
        e.printStackTrace();
    }

}

From source file:webfx.URLVerifier.java

private void discoverThroughHeaders() throws IOException, URISyntaxException {
    // relax redirections
    HttpGet httpGet = new HttpGet(location.toURI());
    HttpClientContext httpcontext = HttpClientContext.create();
    try (CloseableHttpResponse response = httpclient.execute(httpGet, httpcontext)) {
        // get mimetype via Content-Type http header
        Arrays.stream(response.getHeaders("Content-Type")).findFirst()
                .ifPresent(h -> this.contentType = h.getValue());
        if (!Objects.isNull(contentType)) {
            contentType = contentType.contains(";") ? contentType.substring(0, contentType.indexOf(";")).trim()
                    : contentType;// w w w  .  j a v  a2  s . com
            LOGGER.log(Level.INFO, "Final Content-Type: {0}", contentType);
        } else {
            LOGGER.log(Level.INFO, "Content-Type Header is Empty: {0}",
                    Arrays.toString(response.getHeaders("Content-Type")));
            // clear field b/c it was used inside lambda as temp var
            contentType = null;
        }

        // get filename via Content-Disposition http header
        Arrays.stream(response.getHeaders("Content-Disposition")).findFirst()
                .ifPresent(h -> this.pageName = h.getValue());
        if (!Objects.isNull(pageName) && pageName.contains("filename=")) {
            pageName = pageName.substring(pageName.lastIndexOf("filename=") + 9);
            LOGGER.log(Level.INFO, "temporary page name: {0}", pageName);
            if (pageName.indexOf('.') > -1) {
                fileExtension = pageName.substring(pageName.indexOf('.') + 1).trim();
                LOGGER.log(Level.INFO, "Final file extension: {0}", fileExtension);
            }
            pageName = pageName.substring(0, pageName.indexOf('.')).trim();
            LOGGER.log(Level.INFO, "Final page name: {0}", pageName);
        } else {
            // clear field b/c it was used inside lambda as temp var
            pageName = null;
        }

        HttpHost target = httpcontext.getTargetHost();
        List<URI> redirectLocations = httpcontext.getRedirectLocations();
        URI _loc = URIUtils.resolve(httpGet.getURI(), target, redirectLocations);
        this.location = _loc.toURL();
        LOGGER.log(Level.INFO, "Final HTTP location: {0}", _loc.toURL());
    }
}

From source file:es.deustotech.piramide.utils.net.GoogleLocalClient.java

public Vector<Point> getPoints() throws GoogleLocalException {
    final Vector<Point> points = new Vector<Point>();
    int position = 0;
    String start = "0";
    JSONArray pages;//from w  w  w .  j a va 2  s. com
    do {
        try {
            final URI baseURI = new URI(URI[0] + selection + URI[1] + String.valueOf(latitude) + URI[2]
                    + String.valueOf(longitude) + URI[3] + start);
            Log.w("GoogleLocalClient", baseURI.toURL().toString());
            final HttpEntity entity = RestClient.connect(baseURI.toURL().toString(), null);
            final String content = convertStreamToString(entity.getContent());
            final JSONObject jsonObj = new JSONObject(content);
            final JSONObject responseData = jsonObj.getJSONObject("responseData");
            final JSONObject cursor = responseData.getJSONObject("cursor");
            if (!cursor.has("pages"))
                break; // No pages, no results

            pages = cursor.getJSONArray("pages");
            position++;
            if (position < pages.length()) {
                final JSONObject nextPage = pages.getJSONObject(position);
                start = nextPage.getString("start");
            }

            final JSONArray results = responseData.getJSONArray("results");
            for (int i = 0; i < results.length(); ++i) {
                final JSONObject result = results.getJSONObject(i);
                final Point point = new Point(result.getString(Constants.JSON_TITLE),
                        result.getString(Constants.JSON_STREET), result.getString(Constants.JSON_LAT),
                        result.getString(Constants.JSON_LNG));
                points.add(point);
            }

        } catch (Exception e) {
            throw new GoogleLocalException(e.getMessage(), e);
        }
    } while (position < pages.length() && position < MAX_PAGES_TO_PARSE);

    Log.w("GoogleLocalClient", Integer.valueOf(points.size()).toString());

    return points;
}

From source file:com.w20e.socrates.process.RunnerContextImpl.java

@Override
public Configuration getConfiguration() {

    URI qUri = getQuestionnaireId();

    try {//from   w  w  w  .  j a  v  a 2 s.  co  m
        return ConfigurationResource.getInstance().getConfiguration(qUri.toURL());
    } catch (ConfigurationException e) {
        return null;
    } catch (MalformedURLException e) {
        return null;
    }
}

From source file:org.kalypso.kalypsomodel1d2d.sim.ExecuteSWANKalypsoSimulation.java

private Map<String, Object> createInputs(final String pStrExe, final URI pSWANModelPath) {
    final Map<String, Object> inputs = new HashMap<>();
    try {/*w w  w . j  av  a  2 s.  c  om*/
        inputs.put(PreSWANKalypso.CALC_CORE_EXE, pStrExe);
        inputs.put(PreSWANKalypso.OUTPUT_PATH_SWAN, pSWANModelPath.toURL().toExternalForm());
    } catch (final MalformedURLException e) {
        e.printStackTrace();
    }
    return inputs;
}