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:com.github.mhendred.face4j.ResponderImpl.java

/** 
 * @see {@link Responder#doPost(URI, List)}
 *///from  w w  w  .jav  a2  s. c  o m
public String doPost(final URI uri, final List<NameValuePair> params)
        throws FaceClientException, FaceServerException {
    try {
        URL url = uri.toURL();

        StringBuilder strparams = new StringBuilder();
        for (Iterator iterator = params.iterator(); iterator.hasNext();) {
            NameValuePair nameValuePair = (NameValuePair) iterator.next();
            strparams.append(nameValuePair.getName());
            strparams.append("=");
            strparams.append(nameValuePair.getValue());
            strparams.append("&");
        }

        strparams.deleteCharAt(strparams.length() - 1);
        byte[] postData = strparams.toString().getBytes();
        String urlpath = url.toString();
        url = new URL(urlpath + "?" + strparams.toString());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        /*connection.setRequestProperty("X-Custom-Header", "xxx");
        connection.setRequestProperty("Content-Type", "application/json");*/

        // POST the http body data
        //          connection.setDoOutput(true);
        //connection.setRequestMethod("GET");

        /*connection.setRequestProperty( "Content-Length",Integer.toString( postData.length ));
        DataOutputStream  writer = new DataOutputStream(connection.getOutputStream());
        writer.write(postData);
        writer.close();*/

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // OK
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer res = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                res.append(line);
            }
            reader.close();

            return res.toString();

        } else {
            int resp = connection.getResponseCode();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            StringBuffer res = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                res.append(line);
            }
            reader.close();
            return line;
        }

    }

    catch (IOException ioe) {
        throw new FaceClientException(ioe);
    }
}

From source file:org.datavec.api.records.reader.impl.jackson.JacksonRecordReader.java

@Override
public List<Writable> next() {
    if (uris == null)
        throw new IllegalStateException("URIs are null. Not initialized?");
    if (!hasNext())
        throw new NoSuchElementException("No next element");

    URI uri = uris[cursor++];
    invokeListeners(uri);/*from w ww  . ja  v a 2 s .  c om*/
    String fileAsString;
    try {
        fileAsString = FileUtils.readFileToString(new File(uri.toURL().getFile()));
    } catch (IOException e) {
        throw new RuntimeException("Error reading URI file", e);
    }

    return readValues(uri, fileAsString);

}

From source file:org.codehaus.mojo.screenshot.ScreenshotMojo.java

protected void doScreenshot(WebDriver driver, String qualifier, URI uri, String outBaseName)
        throws MalformedURLException {
    if (!(driver instanceof TakesScreenshot)) { // no point in going further
        return;//from  w  w w .  j  av  a2  s  . c o  m
    }
    driver.navigate().to(uri.toURL());
    try {
        TimeUnit.SECONDS.sleep(1); // sleep 1 second to allow for javascript to execute
    } catch (InterruptedException e1) {
    }

    File tempScreenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

    try {
        FileUtils.copyFile(tempScreenshot, new File(outBaseName + "-" + qualifier + ".jpg"));
    } catch (IOException e) {
    }
}

From source file:com.epam.cme.mdp3.core.cfg.Configuration.java

/**
 * Loads and parse CME MDP Configuration.
 *
 * @param uri URI to CME MDP Configuration (config.xml, usually available on CME FTP)
 * @throws ConfigurationException if failed to parse configuration file
 * @throws MalformedURLException  if URI to Configuration is malformed
 */// w  ww.  j  a va 2  s  .  com
private void load(final URI uri) throws ConfigurationException, MalformedURLException {
    // todo: if to implement the same via standard JAXB then dep to apache commons configuration will be not required
    final XMLConfiguration configuration = new XMLConfiguration();
    configuration.setDelimiterParsingDisabled(true);
    configuration.load(uri.toURL());
    for (final HierarchicalConfiguration channelCfg : configuration.configurationsAt("channel")) {
        final ChannelCfg channel = new ChannelCfg(channelCfg.getString("[@id]"),
                channelCfg.getString("[@label]"));

        for (final HierarchicalConfiguration connCfg : channelCfg.configurationsAt("connections.connection")) {
            final String id = connCfg.getString("[@id]");
            final FeedType type = FeedType.valueOf(connCfg.getString("type[@feed-type]"));
            final TransportProtocol protocol = TransportProtocol
                    .valueOf(connCfg.getString("protocol").substring(0, 3));
            final Feed feed = Feed.valueOf(connCfg.getString("feed"));
            final String ip = connCfg.getString("ip");
            final int port = connCfg.getInt("port");
            final List<String> hostIPs = Arrays.asList(connCfg.getStringArray("host-ip"));

            final ConnectionCfg connection = new ConnectionCfg(feed, id, type, protocol, ip, hostIPs, port);
            channel.addConnection(connection);
            connCfgs.put(connection.getId(), connection);
        }
        channelCfgs.put(channel.getId(), channel);
    }
}

From source file:com.turn.camino.config.ConfigBuilder.java

/**
 * Reads config from a location//w  ww . j ava 2s.c  o m
 *
 * @param location location of config
 * @return this
 * @throws IOException
 */
public ConfigBuilder from(URI location) throws IOException {
    InjectableValues inject = new InjectableValues.Std().addValue("location", location);
    addConfig(new ObjectMapper().configure(JsonParser.Feature.ALLOW_COMMENTS, true).setInjectableValues(inject)
            .readValue(location.toURL(), Config.class));
    return this;
}

From source file:org.apache.hadoop.hdfs.server.namenode.ha.StandbyCheckpointer.java

private URL getHttpAddress(Configuration conf) throws IOException {
    final String scheme = DFSUtil.getHttpClientScheme(conf);
    String defaultHost = NameNode.getServiceAddress(conf, true).getHostName();
    URI addr = DFSUtil.getInfoServerWithDefaultHost(defaultHost, conf, scheme);
    return addr.toURL();
}

From source file:be.fedict.trust.service.bean.TrustServiceTrustLinker.java

private String getCrlUrl(X509Certificate childCertificate) {

    URI crlUri = CrlTrustLinker.getCrlUri(childCertificate);
    if (null == crlUri) {
        LOG.warn("No CRL uri for: " + childCertificate.getIssuerX500Principal().toString());
        return null;
    }/*  ww w .j a va  2  s  .  co m*/
    try {
        return crlUri.toURL().toString();
    } catch (MalformedURLException e) {
        LOG.warn("malformed URL: " + e.getMessage(), e);
        return null;
    }
}

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

/**
 * Create a context for the given id.//  ww  w .j  ava2s . co m
 * 
 * @param url
 *            runner config id
 * @throws UnsupportedMediumException
 *             in case the medium isn't supported.
 */
public RunnerContextImpl createContext(final URI url, final Map<String, String> options)
        throws UnsupportedMediumException {

    try {

        Configuration cfg = ConfigurationResource.getInstance().getConfiguration(url.toURL());

        if (cfg == null) {
            return null;
        }

        URI modelId = new URI((String) cfg.getProperty("model.id"));

        LOGGER.fine("Creating model for " + modelId);
        Model model = ModelResource.getInstance().getModel(modelId, cfg);

        LOGGER.finer("Done. Now creating instance");
        Instance inst = ModelResource.getInstance().createInstance(modelId, cfg);

        RenderConfig rCfg = ModelResource.getInstance().getRenderConfig(modelId, cfg);

        LOGGER.finer("Created. Let's create a new context");
        RunnerContextImpl ctx = new RunnerContextImpl(null, getFormatter(url, cfg, options),
                createStateManager(cfg, rCfg, model, inst), model, inst, rCfg);

        // Allow arbitrary properties to be set on the context.
        String key;

        for (final Iterator<?> i = cfg.getKeys(); i.hasNext();) {

            key = (String) i.next();

            if (key.startsWith("context")) {

                ctx.setProperty(key, cfg.getProperty(key));
            }
        }

        return ctx;

    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Couldn't create context", e);
        throw new UnsupportedMediumException(e.getMessage());
    }
}

From source file:io.apiman.manager.api.core.plugin.AbstractPluginRegistry.java

/**
 * Tries to download the plugin from the given remote maven repository.
 *//*w  w  w . ja  v  a 2  s.c o  m*/
protected boolean downloadFromMavenRepo(File pluginFile, PluginCoordinates coordinates, URI mavenRepoUrl) {
    String artifactSubPath = PluginUtils.getMavenPath(coordinates);
    InputStream istream = null;
    OutputStream ostream = null;
    try {
        URL artifactUrl = new URL(mavenRepoUrl.toURL(), artifactSubPath);
        URLConnection connection = artifactUrl.openConnection();
        connection.connect();
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            if (httpConnection.getResponseCode() != 200) {
                throw new IOException();
            }
        }

        istream = connection.getInputStream();
        ostream = new FileOutputStream(pluginFile);
        IOUtils.copy(istream, ostream);
        ostream.flush();
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        IOUtils.closeQuietly(istream);
        IOUtils.closeQuietly(ostream);
    }
}

From source file:dk.defxws.fgssolrremote.OperationsImpl.java

private StringBuffer sendToSolr(String solrCommand, String postParameters) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("sendToSolr solrCommand=" + solrCommand + "\nPost parameters=\n" + postParameters);
    String base = config.getIndexBase(indexName);
    URI uri = new URI(base + solrCommand);
    URL url = uri.toURL();
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    if (postParameters != null) {
        con.setRequestProperty("Content-type", "text/xml; charset=UTF-8");
        con.setRequestMethod("POST");
        con.setDoOutput(true);//from  www.  j a  v a 2  s.  com
        OutputStream out = con.getOutputStream();
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        Reader reader = new StringReader(postParameters);
        char[] buf = new char[1024];
        int read = 0;
        while ((read = reader.read(buf)) >= 0) {
            writer.write(buf, 0, read);
        }
        writer.flush();
        writer.close();
        out.close();
    }

    int responseCode = con.getResponseCode();
    if (logger.isDebugEnabled())
        logger.debug("sendToSolr solrCommand=" + solrCommand + " response Code=" + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    if (logger.isDebugEnabled())
        logger.debug("sendToSolr solrCommand=" + solrCommand + "\n response=" + response);
    return response;
}