Example usage for java.net URL toURI

List of usage examples for java.net URL toURI

Introduction

In this page you can find the example usage for java.net URL toURI.

Prototype

public URI toURI() throws URISyntaxException 

Source Link

Document

Returns a java.net.URI equivalent to this URL.

Usage

From source file:brooklyn.entity.rebind.persister.jclouds.BlobStoreExpiryTest.java

public static HttpToolResponse requestTokenWithExplicitLifetime(URL url, String user, String key,
        Duration expiration) throws URISyntaxException {
    HttpClient client = HttpTool.httpClientBuilder().build();
    HttpToolResponse response = HttpTool.httpGet(client, url.toURI(),
            MutableMap.<String, String>of().add(AuthHeaders.AUTH_USER, user).add(AuthHeaders.AUTH_KEY, key)
                    .add("Host", url.getHost()).add("X-Auth-New-Token", "" + true)
                    .add("X-Auth-Token-Lifetime", "" + expiration.toSeconds()));
    //        curl -v https://ams01.objectstorage.softlayer.net/auth/v1.0/v1.0 -H "X-Auth-User: IBMOS12345-2:username" -H "X-Auth-Key: <API KEY>" -H "Host: ams01.objectstorage.softlayer.net" -H "X-Auth-New-Token: true" -H "X-Auth-Token-Lifetime: 15"
    log.info("Requested token with explicit lifetime: " + expiration + " at " + url + "\n" + response + "\n"
            + response.getHeaderLists());
    return response;
}

From source file:it.cloudicaro.disit.kb.rdf.HttpUtil.java

public static String get(URL url, String accept, String user, String passwd) throws Exception {
    //System.out.println("GET "+url);
    HttpClient client = HttpClients.createDefault();
    HttpGet request = new HttpGet(url.toURI());
    if (accept != null)
        request.addHeader("Accept", accept);

    HttpClientContext context = HttpClientContext.create();
    if (user != null && passwd != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, passwd));

        /*// Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);*/

        // Add AuthCache to the execution context
        context.setCredentialsProvider(credsProvider);
    }/*from ww w .  j  a  v a  2 s  .c  o m*/
    HttpResponse response = client.execute(request, context);

    StatusLine s = response.getStatusLine();
    int code = s.getStatusCode();
    //System.out.println(code);
    if (code != 200)
        throw new Exception(
                "failed access to " + url.toString() + " code: " + code + " " + s.getReasonPhrase());

    Reader reader = null;
    try {
        reader = new InputStreamReader(response.getEntity().getContent());

        StringBuilder sb = new StringBuilder();
        {
            int read;
            char[] cbuf = new char[1024];
            while ((read = reader.read(cbuf)) != -1) {
                sb.append(cbuf, 0, read);
            }
        }

        return sb.toString();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.linecorp.armeria.testing.server.webapp.WebAppContainerTest.java

/**
 * Returns the doc-base directory of the test web application.
 *//*from www . ja  v  a2 s.  co  m*/
public static File webAppRoot() {
    URL url = WebAppContainerTest.class.getProtectionDomain().getCodeSource().getLocation();
    File f;
    try {
        f = new File(url.toURI());
    } catch (URISyntaxException ignored) {
        f = new File(url.getPath());
    }

    final File buildDir;
    if (f.isDirectory()) {
        // f is: testing/build/resources/main
        buildDir = f.getParentFile().getParentFile();
    } else {
        // f is: testing/build/libs/armeria-testing-*.jar
        assert f.isFile();
        buildDir = f.getParentFile().getParentFile();
    }

    assert buildDir.getPath().endsWith("testing" + File.separatorChar + "build");

    final File webAppRoot = new File(buildDir.getParentFile(),
            "src" + File.separatorChar + "main" + File.separatorChar + "webapp");
    assert webAppRoot.isDirectory();
    return webAppRoot;
}

From source file:com.zenika.dorm.maven.test.grinder.GrinderGenerateJson.java

public static void generateJsonAndRepository(File repository) {
    try {//  w w  w. j a v  a  2  s . co m
        URL urlSample = ClassLoader.getSystemResource(SAMPLE_JAR_PATH);
        URL urlJsonFile = ClassLoader.getSystemResource(JSON_PATH);

        LOG.info("Sample URI: " + urlSample.toURI());

        File sample = new File(urlSample.toURI());
        File jsonFile = new File(urlJsonFile.toURI());
        generateJsonAndRepository(repository, sample, jsonFile);
    } catch (URISyntaxException e) {
        throw new RuntimeException("Unable to build Uri with this path: " + repository, e);
    }
}

From source file:no.norrs.projects.andronary.utils.HttpUtil.java

public static HttpResponse GET(URL url, UsernamePasswordCredentials creds)
        throws IOException, URISyntaxException {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), creds);

    HttpGet httpGet = new HttpGet(url.toURI());

    httpGet.addHeader("Accept", "application/json");
    httpGet.addHeader("User-Agent", "Andronary/0.1");
    HttpResponse response;// w ww . j ava2 s  . c o  m

    return httpClient.execute(httpGet);
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.data.QueryResultContainer.java

/**
 * Validates input XML file using 'queryResult.xsd' schema.
 *
 * @param xml xml/*  w w w.  ja v a2  s . c  o  m*/
 * @throws IOException if file is not valid
 */
public static void validateXML(String xml) throws IOException {
    String xsdName = "queryResult.xsd";
    URL resource = QueryResultContainer.class.getClass().getResource(xsdName);
    if (resource == null) {
        throw new IllegalStateException("Cannot locate resource " + xsdName + " on classpath");
    }

    URL xsdFile;
    try {
        xsdFile = resource.toURI().toURL();
    } catch (MalformedURLException | URISyntaxException e) {
        throw new IOException(e);
    }

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        Schema schema = factory.newSchema(xsdFile);
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(new StringReader(xml)));
    } catch (SAXException e) {
        throw new IOException(e);
    }
}

From source file:it.govpay.web.console.utils.HttpClientUtils.java

public static HttpResponse getEsitoPagamento(String urlToInvoke, Logger log) throws Exception {
    HttpResponse responseGET = null;/*  w  w w  .j  a  va 2 s . com*/
    try {
        log.debug("Richiesta Esito del pagamento in corso...");

        URL urlObj = new URL(urlToInvoke);
        HttpHost target = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
        CloseableHttpClient client = HttpClientBuilder.create().disableRedirectHandling().build();
        HttpGet richiestaPost = new HttpGet();

        richiestaPost.setURI(urlObj.toURI());

        log.debug("Invio tramite client Http in corso...");
        responseGET = client.execute(target, richiestaPost);

        if (responseGET == null)
            throw new NullPointerException("La Response HTTP e' null");

        log.debug("Invio tramite client Http completato.");
        return responseGET;
    } catch (Exception e) {
        log.error("Errore durante l'invio della richiesta di pagamento: " + e.getMessage(), e);
        throw e;
    }
}

From source file:com.puppycrawl.tools.checkstyle.utils.CommonUtils.java

/**
 * Resolve the specified filename to a URI.
 * @param filename name os the file//from www.  ja va  2s. c o m
 * @return resolved header file URI
 * @throws CheckstyleException on failure
 */
public static URI getUriByFilename(String filename) throws CheckstyleException {
    // figure out if this is a File or a URL
    URI uri;
    try {
        final URL url = new URL(filename);
        uri = url.toURI();
    } catch (final URISyntaxException | MalformedURLException ignored) {
        uri = null;
    }

    if (uri == null) {
        final File file = new File(filename);
        if (file.exists()) {
            uri = file.toURI();
        } else {
            // check to see if the file is in the classpath
            try {
                final URL configUrl = CommonUtils.class.getResource(filename);
                if (configUrl == null) {
                    throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename);
                }
                uri = configUrl.toURI();
            } catch (final URISyntaxException e) {
                throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename, e);
            }
        }
    }

    return uri;
}

From source file:org.apache.hadoop.gateway.Knox242FuncTest.java

public static int setupLdap() throws Exception {
    URL usersUrl = getResourceUrl("users.ldif");
    ldapTransport = new TcpTransport(0);
    ldap = new SimpleLdapDirectoryServer("dc=hadoop,dc=apache,dc=org", new File(usersUrl.toURI()),
            ldapTransport);/*  w ww.  ja  va2 s  . c om*/
    ldap.start();
    LOG.info("LDAP port = " + ldapTransport.getPort());
    return ldapTransport.getAcceptor().getLocalAddress().getPort();
}

From source file:com.jaeksoft.searchlib.util.LinkUtils.java

public final static URL getLink(URL currentURL, String href, UrlFilterItem[] urlFilterList,
        boolean removeFragment) {

    if (href == null)
        return null;
    href = href.trim();//from   w w  w .  j  a va 2s.c  o m
    if (href.length() == 0)
        return null;

    String fragment = null;
    try {
        URI u = URIUtils.resolve(currentURL.toURI(), href);
        href = u.toString();
        href = UrlFilterList.doReplace(u.getHost(), href, urlFilterList);
        URI uri = URI.create(href);
        uri = uri.normalize();

        String p = uri.getPath();
        if (p != null)
            if (p.contains("/./") || p.contains("/../"))
                return null;

        if (!removeFragment)
            fragment = uri.getRawFragment();

        return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                uri.getQuery(), fragment).normalize().toURL();
    } catch (MalformedURLException e) {
        Logging.info(e.getMessage());
        return null;
    } catch (URISyntaxException e) {
        Logging.info(e.getMessage());
        return null;
    } catch (IllegalArgumentException e) {
        Logging.info(e.getMessage());
        return null;
    }
}