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:cz.incad.Kramerius.audio.AudioHttpRequestForwarder.java

public void forwardGetRequest(URL url) throws IOException, URISyntaxException {
    LOGGER.log(Level.INFO, "forwarding {0}", url);
    HttpGet proxyToRepositoryRequest = new HttpGet(url.toURI());
    forwardSelectedRequestHeaders(clientToProxyRequest, proxyToRepositoryRequest);
    //printRepositoryRequestHeaders(repositoryRequest);
    HttpResponse repositoryToProxyResponse = httpClient.execute(proxyToRepositoryRequest);
    //printRepositoryResponseHeaders(repositoryResponse);
    forwardSelectedResponseHeaders(repositoryToProxyResponse, proxyToClientResponse);
    forwardResponseCode(repositoryToProxyResponse, proxyToClientResponse);
    forwardData(repositoryToProxyResponse.getEntity().getContent(), proxyToClientResponse.getOutputStream());
}

From source file:org.apache.stratos.nginx.extension.NginxStatisticsReader.java

/**
 * Make a http request to http://127.0.0.1:<proxy-port>/nginx_status and find writing count.
 * @param proxyPort//from w  ww . j av  a2 s.  co  m
 * @return
 */
private int findWritingCount(int proxyPort) {
    try {
        URL url = new URL("http", "127.0.0.1", proxyPort, "/nginx_status");
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpUriRequest request = new HttpGet(url.toURI());
        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("http://127.0.0.1:" + proxyPort + "/nginx_status was not found");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output, result = "";
        while ((output = reader.readLine()) != null) {
            result += output;
        }
        Pattern pattern = Pattern.compile("(Writing: )([0-1]*)");
        Matcher matcher = pattern.matcher(result);
        if (matcher.find()) {
            // Deduct one to remove the above request
            int writingCount = Integer.parseInt(matcher.group(2)) - 1;
            if (log.isDebugEnabled()) {
                log.debug(String.format("Writing count: [proxy] %d [value] %d", proxyPort, writingCount));
            }
            return writingCount;
        }
        throw new RuntimeException("Writing block was not found in nginx_status response");
    } catch (HttpHostConnectException ignore) {
        if (ignore.getMessage().contains("Connection refused")) {
            log.warn("Could not find in-flight request count, connection refused: " + "http://127.0.0.1:"
                    + proxyPort + "/nginx_status");
        }
    } catch (Exception e) {
        log.error("Could not find in-flight request count: http://127.0.0.1:" + proxyPort + "/nginx_status", e);
    }
    return 0;
}

From source file:ch.icclab.cyclops.publish.APICaller.java

/**
 * Perform POST query and return Response
 * @param endpoint to be called//from w  ww.ja  va  2 s. c om
 * @param object to be passed
 * @return Response object
 * @throws Exception
 */
public APICaller.Response post(URL endpoint, Object object) throws Exception {
    // prepare connection
    HttpClient client = HttpClientBuilder.create().build();

    // create request
    HttpPost request = new HttpPost(endpoint.toURI());
    StringEntity entity = new StringEntity(new Gson().toJson(object));
    request.addHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");
    request.setEntity(entity);

    // execute response
    HttpResponse response = client.execute(request);
    return new Response(IOUtils.toString(response.getEntity().getContent()),
            response.getStatusLine().getStatusCode());
}

From source file:org.openscore.lang.compiler.modeller.transformers.InputsTransformerTest.java

@Before
public void init() throws URISyntaxException {
    URL resource = getClass().getResource("/operation_with_data.sl");
    ParsedSlang file = yamlParser.parse(SlangSource.fromFile(new File(resource.toURI())));
    Map op = file.getOperation();
    inputsMap = (List) op.get("inputs");
}

From source file:com.arangodb.example.ssl.SslExample.java

@Test
public void sslWithSelfSignedCertificateTest() throws ArangoException, KeyManagementException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, URISyntaxException {

    // create a sslContext for the self signed certificate
    URL resource = this.getClass().getResource(SSL_TRUSTSTORE);
    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(Paths.get(resource.toURI()).toFile(), SSL_TRUSTSTORE_PASSWORD.toCharArray())
            .build();/*from  w w w .  j  a va2s.  c  o  m*/

    ArangoConfigure configuration = new ArangoConfigure("/ssl-arangodb.properties");
    configuration.setSslContext(sslContext);
    configuration.init();

    ArangoDriver arangoDriver = new ArangoDriver(configuration);

    ArangoVersion version = arangoDriver.getVersion();
    Assert.assertNotNull(version);
}

From source file:org.basinmc.maven.plugins.minecraft.AbstractArtifactMojo.java

/**
 * Fetches any resource from a remote HTTP server and stores it in a specified file.
 *///from   ww  w.j  a  v a  2  s  .c o  m
protected void fetch(@Nonnull URL url, @Nonnull Path target) throws IOException {
    try {
        this.fetch(url.toURI(), target);
    } catch (URISyntaxException ex) {
        throw new IOException("Invalid resource URI: " + ex.getMessage(), ex);
    }
}

From source file:net.sourceforge.dita4publishers.tools.dxp.DxpFileOrganizingBosVisitor.java

public void visit(BoundedObjectSet bos) throws Exception {
    // If there is a root map, then everything is
    // handled relative to it and there may not be a need
    // for a manifest, otherwise we need to generate 
    // a manifest map or reorganize the files to put
    // everything below the root map.

    BosMember rootMember = bos.getRoot();
    if (rootMember != null && rootMember instanceof DitaMapBosMemberImpl) {
        this.rootMap = rootMember;
    } else {//from  ww  w.  j a  v a2s .  c om
        this.rootMap = constructDxpManifestMap(bos);
    }

    this.rootMapUri = rootMap.getEffectiveUri();
    try {
        this.baseUri = AddressingUtil.getParent(rootMapUri);
    } catch (URISyntaxException e) {
        throw new BosException("URI syntax exception calculating base URI for root map: " + e.getMessage());
    } catch (MalformedURLException e) {
        throw new BosException("MalformedURLException calculating base URI for root map: " + e.getMessage());
    } catch (IOException e) {
        throw new BosException("IOException calculating base URI for root map: " + e.getMessage());
    }

    this.rewriteRequired = false;

    for (BosMember member : bos.getMembers()) {
        if (member.equals(rootMap))
            continue;
        URI memberUri = member.getEffectiveUri();
        URI memberBase = null;
        try {
            memberBase = AddressingUtil.getParent(memberUri);
        } catch (URISyntaxException e) {
            throw new BosException(
                    "URI syntax exception: " + e.getMessage() + " getting base URI for member " + member);
        } catch (MalformedURLException e) {
            throw new BosException(
                    "MalformedURLException: " + e.getMessage() + " getting base URI for member " + member);
        } catch (IOException e) {
            throw new BosException("IOException: " + e.getMessage() + " getting base URI for member " + member);
        }
        URI relativeUri = baseUri.relativize(memberUri);
        boolean isAbsolute = relativeUri.isAbsolute();
        if (isAbsolute || relativeUri.toString().startsWith("..") || relativeUri.toString().startsWith("/")
                || memberBase.equals(baseUri)) {
            // URI is not below the root map, need to rewrite it.
            rewriteRequired = true;
            try {
                URL newUrl = new URL(baseUri.toURL(), "dependencies/" + member.getFileName());
                member.setEffectiveUri(newUrl.toURI());
            } catch (MalformedURLException e) {
                throw new BosException("Malformed URL exception: " + e.getMessage()
                        + " constructing new URL for member " + member);
            } catch (URISyntaxException e) {
                throw new BosException("URI syntax exception: " + e.getMessage()
                        + " constructing new URI for member " + member);
            }
        }
    }

    if (rewriteRequired) {
        UriToUriPointerRewritingBosVisitor rewritingVisitor = new UriToUriPointerRewritingBosVisitor();
        rewritingVisitor.visit(bos);
    }

}

From source file:au.com.redboxresearchdata.harvester.httpclient.BasicHttpClient.java

/**
 * Gets an HTTP client. If authentication is required, the authenticate()
 * method must be called prior to this method.
 * /*from w w w.  j a v  a  2 s.c om*/
 * @param auth set true to use authentication, false to skip authentication
 * @return an HTTP client
 */
public HttpClient getHttpClient(boolean auth) {
    HttpClient client = new HttpClient();
    try {
        URL url = new URL(baseUrl);
        //        log.info(baseUrl + "----------------------------1111------------");
        Proxy proxy = ProxySelector.getDefault().select(url.toURI()).get(0);
        if (!proxy.type().equals(Proxy.Type.DIRECT)) {
            InetSocketAddress address = (InetSocketAddress) proxy.address();
            String proxyHost = address.getHostName();
            int proxyPort = address.getPort();
            client.getHostConfiguration().setProxy(proxyHost, proxyPort);
            //          log.trace("Using proxy {}:{}", proxyHost, proxyPort);
        }
    } catch (Exception e) {
        //    log.warn("Failed to get proxy settings: " + e.getMessage());
    }
    if (auth && credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
        //  log.trace("Credentials: username={}", credentials.getUserName());
    }
    return client;
}

From source file:com.runwaysdk.dataaccess.io.RunwayClasspathEntityResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    if (systemId.startsWith("classpath:")) {
        systemId = systemId.replaceFirst("classpath:", "");
    } else {//from   w w  w  .  j  a  va  2s  . co  m
        return null;
    }

    // We're fetching from the root classloader, which means the equivalent of having a / at the beginning of the path
    // For some reason, when you do put a preceeding / the root classloader won't find the resource. This is dumb so I'm
    // going to remove preceeding slashes to stop it from not finding a valid resource.
    if (systemId.startsWith("/")) {
        systemId = systemId.replaceFirst("/", "");
    }

    InputSource inputSource = null;

    try {
        URL url = this.getClass().getClassLoader().getResource(systemId);

        if (url == null) {
            throw new Exception("ClassLoader.getResource returned null.");
        }

        inputSource = new InputSource(url.toURI().toString());

        if (inputSource.getSystemId() == null) {
            throw new Exception(
                    "ClassLoader.getResource returned a url, but inputSource.getSystemId returned null.");
        }

        log.debug("Runway SAX parser successfully resolved resource on classpath [" + systemId + "] to ["
                + inputSource.getSystemId() + "].");

        return inputSource;
    } catch (Exception e) {
        log.fatal("Runway SAX parser unable to resolve resource on classpath [" + systemId + "].", e);
        return null;
    }
}

From source file:com.sastix.cms.server.services.content.HashedDirectoryServiceTest.java

@Before
public void init() throws URISyntaxException {
    VOLUME = temporaryFolder.getRoot() + "/";
    ((HashedDirectoryServiceImpl) hashedDirectoryService).setVolume(VOLUME);
    LOGGER.info("Test volume directory {}", VOLUME);
    final URL localFile = getClass().getClassLoader().getResource("./logo.png");
    localUri = localFile.toURI();
}