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.ebayopensource.turmeric.runtime.tests.common.sif.tester.ServicePayloadExecutor.java

public void setServiceURL(URI uri) throws MalformedURLException {
    setServiceURL(uri.toURL());
}

From source file:dk.itst.oiosaml.sp.service.util.HttpSOAPClient.java

public Envelope wsCall(String location, String username, String password, boolean ignoreCertPath, String xml,
        String soapAction) throws IOException, SOAPException {
    URI serviceLocation;
    try {//from w ww .j  ava2s  .c  o m
        serviceLocation = new URI(location);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid uri for artifact resolve: " + location);
    }
    if (log.isDebugEnabled())
        log.debug("serviceLocation..:" + serviceLocation);
    if (log.isDebugEnabled())
        log.debug("SOAP Request: " + xml);

    HttpURLConnection c = (HttpURLConnection) serviceLocation.toURL().openConnection();
    if (c instanceof HttpsURLConnection) {
        HttpsURLConnection sc = (HttpsURLConnection) c;

        if (ignoreCertPath) {
            sc.setSSLSocketFactory(new DummySSLSocketFactory());
            sc.setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
    }
    c.setAllowUserInteraction(false);
    c.setDoInput(true);
    c.setDoOutput(true);
    c.setFixedLengthStreamingMode(xml.getBytes("UTF-8").length);
    c.setRequestMethod("POST");
    c.setReadTimeout(20000);
    c.setConnectTimeout(30000);

    addContentTypeHeader(xml, c);
    c.addRequestProperty("SOAPAction", "\"" + (soapAction == null ? "" : soapAction) + "\"");

    if (username != null && password != null) {
        c.addRequestProperty("Authorization",
                "Basic " + Base64.encodeBytes((username + ":" + password).getBytes(), Base64.DONT_BREAK_LINES));
    }
    OutputStream outputStream = c.getOutputStream();
    IOUtils.write(xml, outputStream, "UTF-8");
    outputStream.flush();
    outputStream.close();

    if (c.getResponseCode() == 200) {
        InputStream inputStream = c.getInputStream();
        String result = IOUtils.toString(inputStream, "UTF-8");
        inputStream.close();

        if (log.isDebugEnabled())
            log.debug("Server SOAP response: " + result);
        XMLObject res = SAMLUtil.unmarshallElementFromString(result);

        Envelope envelope = (Envelope) res;
        if (SAMLUtil.getFirstElement(envelope.getBody(), Fault.class) != null) {
            log.warn(
                    "Result has soap11:Fault, but server returned 200 OK. Treating as error, please fix the server");
            throw new SOAPException(c.getResponseCode(), result);
        }
        return envelope;
    } else {
        log.debug("Response code: " + c.getResponseCode());

        InputStream inputStream = c.getErrorStream();
        String result = IOUtils.toString(inputStream, "UTF-8");
        inputStream.close();
        if (log.isDebugEnabled())
            log.debug("Server SOAP fault: " + result);

        throw new SOAPException(c.getResponseCode(), result);
    }
}

From source file:eu.esdihumboldt.hale.common.cache.Request.java

/**
 * This function handles all Request and does the caching.
 * /*from  w ww .j  a  v a  2  s  . c o  m*/
 * @param uri to file
 * 
 * @return an {@link InputStream} to uri
 * 
 * @throws Exception if something goes wrong
 */
public InputStream get(URI uri) throws Exception {
    String scheme = uri.getScheme();

    if (!scheme.equals("http") && !scheme.equals("https")) { //$NON-NLS-1$
        // get non-HTTP(S) resources through URL.openStream
        return getLocal(uri.toURL());
    }

    // no caching activated
    if (!cacheEnabled) {
        return openStream(uri);
    }

    String key = uri.toString(); // removeSpecialChars(uri.toString());
    Cache cache = null;
    Element element = null;
    if (cacheEnabled) {
        // get the current cache for web requests
        cache = HaleCacheManager.getInstance().getCache(CACHE_NAME);

        element = cache.get(key);
    }

    if (element == null) {
        // if the entry does not exist fetch it from the web
        InputStream in = openStream(uri);
        byte[] data;
        try {
            data = ByteStreams.toByteArray(in);
        } finally {
            in.close();
        }

        if (cache != null) {
            // and add it to the cache
            cache.put(new Element(key, data));
        }

        return new ByteArrayInputStream(data);
    } else {
        byte[] data = (byte[]) element.getObjectValue();
        return new ByteArrayInputStream(data);
    }
}

From source file:org.couchpotato.CouchPotato.java

private <T> T command(String command, String arguments, Type type)
        throws MalformedURLException, IOException, SocketTimeoutException {
    try {//  ww  w  .ja  v  a  2  s.  co m
        URI uri = this.getUri(command, arguments);
        // this WILL throw a EOFexception if it gets a HTTP 301 response because it wont follow it
        // so ALL URLS MUST BE PERFECT!!!!
        HttpURLConnection server = (HttpURLConnection) uri.toURL().openConnection();
        // TODO going to try and not use this and see if everything works out
        //         if ( uri.getScheme().compareTo("https") == 0 ) {
        //            server = (HttpsURLConnection)uri.toURL().openConnection();
        //         } else {
        //            server = (HttpURLConnection)uri.toURL().openConnection();
        //         }
        server.setConnectTimeout(SOCKET_TIMEOUT);
        Reader reader = new BufferedReader(new InputStreamReader(server.getInputStream()));
        // TypeToken cannot figure out T so instead it must be supplied
        GsonBuilder build = new GsonBuilder();
        build.registerTypeAdapter(JsonBoolean.class, new JsonBooleanDeserializer());
        T response;
        if (type == MovieListJson.class) {
            response = (T) build.create().fromJson(reader, _NewAPI_MovieListJson.class).toOld();
        } else {
            response = build.create().fromJson(reader, type);
        }
        return response;
    } catch (URISyntaxException e) {
        throw new MalformedURLException(e.getMessage());
    }
}

From source file:com.liferay.maven.plugins.ServiceBuilderMojo.java

protected void initPortalClassLoader() throws Exception {
    super.initPortalClassLoader();

    Class<?> clazz = getClass();

    URLClassLoader urlClassLoader = (URLClassLoader) clazz.getClassLoader();

    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);

    method.setAccessible(true);//from  ww w.  j a  v a2 s .c  o m

    File file = new File(implResourcesDir);

    URI uri = file.toURI();

    method.invoke(urlClassLoader, uri.toURL());
}

From source file:org.gatherdata.alert.notify.mail.internal.EmailNotifier.java

public boolean canSendTo(URI notificationAddress) {
    log.debug("canSendTo(" + notificationAddress + ")");
    log.debug("\t scheme:" + notificationAddress.getScheme());
    log.debug("\t scheme specific:" + notificationAddress.getSchemeSpecificPart());
    log.debug("\t fragment:" + notificationAddress.getFragment());
    log.debug("\t host:" + notificationAddress.getHost());
    log.debug("\t path:" + notificationAddress.getPath());
    try {//from   ww  w . j av a  2s.  c om
        log.debug("\t as URL:" + notificationAddress.toURL());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return SCHEME_TYPES.contains(notificationAddress.getScheme());
}

From source file:org.cloudfoundry.maven.AbstractCloudFoundryMojo.java

private CloudFoundryClient createConnection(CloudCredentials credentials, URI target, String org, String space,
        boolean trustSelfSignedCert) throws MojoExecutionException {
    try {/*  ww w .j av  a  2s . c  om*/
        CloudFoundryClient cloudFoundryClient = new CloudFoundryClient(credentials, target.toURL(), org, space,
                getHttpProxyConfiguration(target), trustSelfSignedCert);
        cloudFoundryClient.setResponseErrorHandler(responseErrorHandler);
        return cloudFoundryClient;
    } catch (MalformedURLException e) {
        throw new MojoExecutionException(String.format(
                "Incorrect Cloud Foundry target URL '%s'. Make sure the URL contains a scheme, e.g. http://...",
                target), e);
    }
}

From source file:no.met.jtimeseries.service.TimeSeriesService.java

/**
 * Get location forecast schema url/*from   www .  j a  v  a2s .  co  m*/
 * @return location forecast schema url or null
 */
private URL getLocationForecastSchemaUrl() {
    try {
        ConfigUtils cfg = new no.met.halo.common.ConfigUtils("/config/jtimeseries.properties", JTIMESERIES_ENV);
        String scheme = cfg.getRequired("datasource.scheme");
        String server = cfg.getRequired("datasource.server");
        String port = cfg.getRequired("datasource.port");
        String path = cfg.getRequired("datasource.meteogram.path");

        URI uri = new URI(scheme, server + ":" + port, path + "schema", null, null);
        return uri.toURL();
    } catch (URISyntaxException ex) {
        Logger.getLogger(TimeSeriesService.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
    } catch (MalformedURLException ex) {
        Logger.getLogger(TimeSeriesService.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
    }
    return null;
}

From source file:alpine.Config.java

/**
 * Extends the runtime classpath to include the files or directories specified.
 * @param files one or more File objects representing a single JAR file or a directory containing JARs.
 * @since 1.0.0//from  ww w.j  a  v a 2  s. co  m
 */
public void expandClasspath(File... files) {
    URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<URLClassLoader> urlClass = URLClassLoader.class;
    for (File file : files) {
        LOGGER.info("Expanding classpath to include: " + file.getAbsolutePath());
        URI fileUri = file.toURI();
        try {
            Method method = urlClass.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(urlClassLoader, fileUri.toURL());
        } catch (MalformedURLException | NoSuchMethodException | IllegalAccessException
                | InvocationTargetException e) {
            LOGGER.error("Error expanding classpath", e);
        }
    }
}

From source file:org.aludratest.testcase.data.impl.xml.XmlBasedTestDataProvider.java

private InputStream tryFindXml(String uri, Method testMethod)
        throws IOException, AutomationException, URISyntaxException {
    if (uri.matches("[a-z]+://.*")) {
        URI realUri = new URI(uri);
        URL url = realUri.toURL();
        return url.openStream();
    }/*  w ww .  j  a  v a 2 s.com*/

    // first search try: full path, as used for Excels
    StringBuilder sbPath = new StringBuilder();
    sbPath.append(aludraConfig.getXlsRootPath());

    if (sbPath.toString().endsWith(File.separator)) {
        sbPath.delete(sbPath.length() - 1, sbPath.length());
    }
    sbPath.append(File.separator);
    sbPath.append(testMethod.getDeclaringClass().getName().replace(".", File.separator));
    sbPath.append(File.separator);
    sbPath.append(uri);
    File f = new File(sbPath.toString());
    if (f.isFile()) {
        return new FileInputStream(f);
    }

    // second try: directly under root path
    sbPath = new StringBuilder();
    sbPath.append(aludraConfig.getXlsRootPath());

    if (sbPath.toString().endsWith(File.separator)) {
        sbPath.delete(sbPath.length() - 1, sbPath.length());
    }
    sbPath.append(File.separator);
    sbPath.append(uri);
    f = new File(sbPath.toString());
    if (f.isFile()) {
        return new FileInputStream(f);
    }

    throw new AutomationException("Could not find test data XML file " + uri);
}