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.lin.web.service.impl.GAEClientConnection.java

@Override
public void sendRequestHeader(HttpRequest request) throws HttpException, IOException {
    try {//w  w w.  jav a 2  s.  c om
        HttpHost host = route.getTargetHost();

        URI uri = new URI(host.getSchemeName() + "://" + host.getHostName()
                + ((host.getPort() == -1) ? "" : (":" + host.getPort())) + request.getRequestLine().getUri());

        this.request = new HTTPRequest(uri.toURL(), HTTPMethod.valueOf(request.getRequestLine().getMethod()),
                FetchOptions.Builder.disallowTruncate().doNotFollowRedirects());
    } catch (URISyntaxException ex) {
        throw new IOException("Malformed request URI: " + ex.getMessage(), ex);
    } catch (IllegalArgumentException ex) {
        throw new IOException("Unsupported HTTP method: " + ex.getMessage(), ex);
    }

    //     System.err.println("SEND: " + this.request.getMethod() + " " + this.request.getURL());

    for (Header h : request.getAllHeaders()) {
        //       System.err.println("SEND: " + h.getName() + ": " + h.getValue());
        this.request.addHeader(new HTTPHeader(h.getName(), h.getValue()));
    }
}

From source file:ru.algorithmist.jquant.infr.GAEClientConnection.java

@Override
public void sendRequestHeader(HttpRequest request) throws HttpException, IOException {
    try {/*from  w  ww.  j  a  v  a2  s. c o  m*/
        HttpHost host = route.getTargetHost();

        URI uri = new URI(host.getSchemeName() + "://" + host.getHostName()
                + ((host.getPort() == -1) ? "" : (":" + host.getPort())) + request.getRequestLine().getUri());

        this.request = new HTTPRequest(uri.toURL(), HTTPMethod.valueOf(request.getRequestLine().getMethod()),
                FetchOptions.Builder.disallowTruncate().doNotFollowRedirects());

    } catch (URISyntaxException ex) {
        throw new IOException("Malformed request URI: " + ex.getMessage(), ex);
    } catch (IllegalArgumentException ex) {
        throw new IOException("Unsupported HTTP method: " + ex.getMessage(), ex);
    }

    for (Header h : request.getAllHeaders()) {
        this.request.addHeader(new HTTPHeader(h.getName(), h.getValue()));
    }
}

From source file:msearch.filmlisten.MSFilmlisteLesen.java

private InputStream getInputStreamForLocation(String source) throws Exception {
    InputStream in;/*from   www  .j a v  a  2s . c om*/
    long size = 0;
    final URI uri;
    if (source.startsWith("http")) {
        uri = new URI(source);
        //remote address for internet download
        HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        conn.setRequestProperty("User-Agent", MSConfig.getUserAgent());
        if (conn.getResponseCode() < 400) {
            size = conn.getContentLengthLong();
        }
        in = new SizeInputStream(conn.getInputStream(), size, uri.toASCIIString());
    } else {
        //local file
        notifyProgress(source, "Download", PROGRESS_MAX);
        in = new FileInputStream(source);
    }

    return in;
}

From source file:freemarker.test.servlet.WebAppTestCase.java

protected final HTTPResponse getHTTPResponse(String webAppName, String webAppRelURL) throws Exception {
    if (webAppName.startsWith("/") || webAppName.endsWith("/")) {
        throw new IllegalArgumentException("\"webAppName\" can't start or end with \"/\": " + webAppName);
    }/*w  ww .j  a  v  a  2  s .co  m*/
    if (webAppRelURL.startsWith("/") || webAppRelURL.endsWith("/")) {
        throw new IllegalArgumentException("\"webappRelURL\" can't start or end with \"/\": " + webAppRelURL);
    }

    ensureWebAppIsDeployed(webAppName);

    final URI uri = new URI("http://localhost:" + server.getConnectors()[0].getLocalPort() + "/" + webAppName
            + "/" + webAppRelURL);

    final HttpURLConnection httpCon = (HttpURLConnection) uri.toURL().openConnection();
    httpCon.connect();
    try {
        LOG.debug("HTTP GET: {}", uri);

        final int responseCode = httpCon.getResponseCode();

        final String content;
        if (responseCode == 200) {
            InputStream in = httpCon.getInputStream();
            try {
                content = IOUtils.toString(in, "UTF-8");
            } finally {
                in.close();
            }
        } else {
            content = null;
        }

        return new HTTPResponse(responseCode, httpCon.getResponseMessage(), content, uri);
    } finally {
        httpCon.disconnect();
    }
}

From source file:org.graylog2.rules.DroolsEngine.java

private byte[] createKJar(KieServices ks, ReleaseId releaseId, String pom, String... drls)
        throws RulesCompilationException {
    KieFileSystem kfs = ks.newKieFileSystem();
    if (pom != null) {
        kfs.write("pom.xml", pom);
    } else {//from   w  w w. j ava 2 s . c o m
        kfs.generateAndWritePomXML(releaseId);
    }
    for (int i = 0; i < drls.length; i++) {
        if (drls[i] != null) {
            kfs.write("src/main/resources/r" + i + ".drl", drls[i]);
        }
    }
    for (URI builtinRuleUrl : builtinRuleUrls) {
        final String rulesFileName = FilenameUtils.getName(builtinRuleUrl.getPath());
        final String path = "src/main/resources/" + rulesFileName;
        final URL url;
        try {
            url = builtinRuleUrl.toURL();
        } catch (MalformedURLException e) {
            throw new RulesCompilationException(Collections.<org.kie.api.builder.Message>emptyList());
        }

        final Resource resource = ResourceFactory.newUrlResource(url).setSourcePath(path)
                .setResourceType(ResourceType.DRL);
        kfs.write(resource);
    }

    final KieBuilder kb = ks.newKieBuilder(kfs).buildAll();
    if (kb.getResults().hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
        throw new RulesCompilationException(kb.getResults().getMessages());
    }
    final InternalKieModule kieModule = (InternalKieModule) ks.getRepository().getKieModule(releaseId);

    return kieModule.getBytes();
}

From source file:nl.esciencecenter.ptk.csv.CSVData.java

public void readFile(URI file) throws MalformedURLException, IOException {
    ResourceLoader loader = ResourceLoader.getDefault();
    String txt = loader.readText(file.toURL());
    this.parseText(txt);
}

From source file:net.ychron.unirestinst.http.HttpClientHelper.java

private HttpRequestBase prepareRequest(HttpRequest request, boolean async) {

    Object defaultHeaders = options.getOption(Option.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        @SuppressWarnings("unchecked")
        Set<Entry<String, String>> entrySet = ((Map<String, String>) defaultHeaders).entrySet();
        for (Entry<String, String> entry : entrySet) {
            request.header(entry.getKey(), entry.getValue());
        }//from w ww .  j a  v a  2 s  .c o  m
    }

    if (!request.getHeaders().containsKey(USER_AGENT_HEADER)) {
        request.header(USER_AGENT_HEADER, USER_AGENT);
    }
    if (!request.getHeaders().containsKey(ACCEPT_ENCODING_HEADER)) {
        request.header(ACCEPT_ENCODING_HEADER, "gzip");
    }

    HttpRequestBase reqObj = null;

    String urlToRequest = null;
    try {
        URL url = new URL(request.getUrl());
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(),
                URLDecoder.decode(url.getPath(), "UTF-8"), "", url.getRef());
        urlToRequest = uri.toURL().toString();
        if (url.getQuery() != null && !url.getQuery().trim().equals("")) {
            if (!urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
                urlToRequest += "?";
            }
            urlToRequest += url.getQuery();
        } else if (urlToRequest.substring(urlToRequest.length() - 1).equals("?")) {
            urlToRequest = urlToRequest.substring(0, urlToRequest.length() - 1);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    switch (request.getHttpMethod()) {
    case GET:
        reqObj = new HttpGet(urlToRequest);
        break;
    case POST:
        reqObj = new HttpPost(urlToRequest);
        break;
    case PUT:
        reqObj = new HttpPut(urlToRequest);
        break;
    case DELETE:
        reqObj = new HttpDeleteWithBody(urlToRequest);
        break;
    case PATCH:
        reqObj = new HttpPatchWithBody(urlToRequest);
        break;
    case OPTIONS:
        reqObj = new HttpOptions(urlToRequest);
        break;
    case HEAD:
        reqObj = new HttpHead(urlToRequest);
        break;
    }

    Set<Entry<String, List<String>>> entrySet = request.getHeaders().entrySet();
    for (Entry<String, List<String>> entry : entrySet) {
        List<String> values = entry.getValue();
        if (values != null) {
            for (String value : values) {
                reqObj.addHeader(entry.getKey(), value);
            }
        }
    }

    // Set body
    if (!(request.getHttpMethod() == HttpMethod.GET || request.getHttpMethod() == HttpMethod.HEAD)) {
        if (request.getBody() != null) {
            HttpEntity entity = request.getBody().getEntity();
            if (async) {
                if (reqObj.getHeaders(CONTENT_TYPE) == null || reqObj.getHeaders(CONTENT_TYPE).length == 0) {
                    reqObj.setHeader(entity.getContentType());
                }
                try {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    entity.writeTo(output);
                    NByteArrayEntity en = new NByteArrayEntity(output.toByteArray());
                    ((HttpEntityEnclosingRequestBase) reqObj).setEntity(en);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                ((HttpEntityEnclosingRequestBase) reqObj).setEntity(entity);
            }
        }
    }

    return reqObj;
}

From source file:org.apache.axis2.jaxws.util.ModuleWSDLLocator.java

/**
 * Return the wsdlLocation in URL form. WsdlLocation could be URL, relative
 * module path, full absolute path./*from   w w w .  jav a 2 s  .co m*/
 * 
 * @param wsdlLocation
 *            the location of a WSDL document in the form of a URL string, a
 *            relative pathname (relative to the root of a module, or a
 *            full-qualified absolute pathname
 * @return the location of the WSDL document in the form of a URL
 */
public URL getWsdlUrl(String wsdlLocation) {
    URL streamURL = null;
    InputStream is = null;
    URI pathURI = null;

    try {
        streamURL = new URL(wsdlLocation);
        is = streamURL.openStream();
        is.close();
    } catch (Throwable t) {
        // No FFDC required
    }

    if (is == null) {
        try {
            pathURI = new URI(wsdlLocation);
            streamURL = pathURI.toURL();
            is = streamURL.openStream();
            is.close();
        } catch (Throwable t) {
            // No FFDC required
        }
    }

    if (is == null) {
        try {
            File file = new File(wsdlLocation);
            streamURL = file.toURL();
            is = streamURL.openStream();
            is.close();
        } catch (Throwable t) {
            // No FFDC required
        }
    }

    if (log.isDebugEnabled() && streamURL == null) {
        log.debug("Absolute wsdlLocation could not be determined: " + wsdlLocation);
    }

    return streamURL;
}

From source file:fi.csc.shibboleth.mobileauth.impl.authn.ResolveAuthenticationStatus.java

/**
 * Fetch status update from the backend//from  w  w  w  .j  a va 2s . co  m
 * 
 * @param conversationKey
 * @param profileCtx
 * @param mobCtx
 */
private void getStatusUpdate(String conversationKey, ProfileRequestContext profileCtx, MobileContext mobCtx) {
    log.debug("{} Getting statusUpdate for convKey {}", getLogPrefix(), conversationKey);

    final CloseableHttpClient httpClient;
    try {
        log.debug("{} Trying to create httpClient", getLogPrefix());
        httpClient = createHttpClient();
    } catch (KeyStoreException | RuntimeException e) {
        log.error("{} Cannot create httpClient", getLogPrefix(), e);
        ActionSupport.buildEvent(profileCtx, EventIds.RUNTIME_EXCEPTION);
        return;
    }

    HttpEntity entity = null;

    try {
        final URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(authServer).setPort(authPort).setPath(statusPath)
                .setParameter("communicationDataKey", conversationKey);

        final URI url = builder.build();
        log.debug("{} getStatus URL: {}", getLogPrefix(), url.toURL());

        final HttpGet httpGet = new HttpGet(url);
        final Gson gson = new GsonBuilder().create();

        final CloseableHttpResponse response = httpClient.execute(httpGet);
        log.debug("{} Response: {}", getLogPrefix(), response);

        int statusCode = response.getStatusLine().getStatusCode();
        log.debug("{}HTTPStatusCode {}", getLogPrefix(), statusCode);

        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            log.error("{} Authentication failed for {} with error [{}]", getLogPrefix(),
                    mobCtx.getMobileNumber(), statusCode);
            mobCtx.setProcessState(ProcessState.ERROR);
            ActionSupport.buildEvent(profileCtx, EventIds.RUNTIME_EXCEPTION);
            return;
        }

        if (statusCode == HttpStatus.SC_OK) {

            entity = response.getEntity();
            final String json = EntityUtils.toString(entity, "UTF-8");

            final StatusResponse status = gson.fromJson(json, StatusResponse.class);

            log.debug("{} Gson commKey: {}", getLogPrefix(), status.getCommunicationDataKey());
            log.debug("{} Gson EventID: {}", getLogPrefix(), status.getEventId());
            log.debug("{} Gson ErrorMessage: {}", getLogPrefix(), status.getErrorMessage());

            response.close();

            final Map<String, String> attributes = status.getAttributes();

            if (status.getErrorMessage() == null && !MapUtils.isEmpty(attributes)) {

                log.info("{} Authentication completed for {}", getLogPrefix(), mobCtx.getMobileNumber());
                mobCtx.setProcessState(ProcessState.COMPLETE);
                mobCtx.setAttributes(status.getAttributes());

                if (log.isDebugEnabled()) {
                    for (Map.Entry<String, String> attr : status.getAttributes().entrySet()) {
                        log.debug("Attr: {} - Value: {}", attr.getKey(), attr.getValue());
                    }
                }

            } else if (status.getErrorMessage() != null) {
                log.info("{} Authentication failed for {} with error [{}]", getLogPrefix(),
                        mobCtx.getMobileNumber(), status.getErrorMessage());
                mobCtx.setProcessState(ProcessState.ERROR);
                mobCtx.setErrorMessage(status.getErrorMessage());
            } else {
                log.info("{} Authentication in process for {}", getLogPrefix(), mobCtx.getMobileNumber());
                mobCtx.setProcessState(ProcessState.IN_PROCESS);
            }

        } else {
            mobCtx.setProcessState(ProcessState.ERROR);
            log.error("{} Unexpected status code {} from REST gateway", getLogPrefix(), statusCode);
            ActionSupport.buildEvent(profileCtx, EVENTID_GATEWAY_ERROR);
            return;
        }

    } catch (Exception e) {
        log.error("Exception: {}", e);
        ActionSupport.buildEvent(profileCtx, EventIds.RUNTIME_EXCEPTION);
        return;
    } finally {
        EntityUtils.consumeQuietly(entity);
    }

}

From source file:com.mirth.connect.connectors.ws.WebServiceConnectorService.java

private Future<WsdlInterface> importWsdlInterface(final WsdlProject wsdlProject, final URI newWsdlUrl,
        final WsdlLoader wsdlLoader) {
    ExecutorService executor = Executors.newSingleThreadExecutor();

    return executor.submit(new Callable<WsdlInterface>() {
        public WsdlInterface call() throws Exception {
            WsdlInterface[] wsdlInterfaces = WsdlInterfaceFactory.importWsdl(wsdlProject,
                    newWsdlUrl.toURL().toString(), false, wsdlLoader);
            return wsdlInterfaces[0];
        }//from   www .  j a  v  a2 s. co  m
    });
}