Example usage for java.net URL getPort

List of usage examples for java.net URL getPort

Introduction

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

Prototype

public int getPort() 

Source Link

Document

Gets the port number of this URL .

Usage

From source file:org.signserver.client.cli.performance.PerformanceTestPDFServlet.java

License:asdf

/** @see org.signserver.client.PerformanceTestTask */
public boolean invoke(int threadId) {
    if (startTime == 0) {
        startTime = System.currentTimeMillis();
    }//from  w  ww  .  ja  v  a  2 s.co m
    byte[] testPDF = pdfs
            .get((int) ((System.currentTimeMillis() - startTime) * ((long) pdfs.size()) / runTime));
    URL target;
    try {
        target = new URL(baseURLString);
        InetAddress addr = InetAddress.getByName(target.getHost());
        Socket socket = new Socket(addr, target.getPort());
        OutputStream raw = socket.getOutputStream();
        final int contentLength = REQUEST_CONTENT_WORKERNAME.length() + REQUEST_CONTENT_FILE.length()
                + testPDF.length + REQUEST_CONTENT_END.length();
        final String command = "POST " + target.getPath() + "pdf HTTP/1.0\r\n"
                + "Content-Type: multipart/form-data; boundary=signserver\r\n" + "Content-Length: "
                + contentLength + "\r\n" + "\r\n";
        raw.write(command.getBytes());
        raw.write(REQUEST_CONTENT_WORKERNAME.getBytes());
        raw.write(REQUEST_CONTENT_FILE.getBytes());
        raw.write(testPDF);
        raw.write(REQUEST_CONTENT_END.getBytes());
        raw.flush();

        InputStream in = socket.getInputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        in.close();
        os.close();
        byte[] inbytes = os.toByteArray();

        PdfReader pdfReader = new PdfReader(inbytes);
        if (!new String(pdfReader.getPageContent(1)).contains(PDF_CONTENT)) {
            System.err.println("Did not get the same document back..");
            return false;
        }
        pdfReader.close();
        raw.close();
        socket.close();
    } catch (IOException e) {
        System.err.println("testPDF.length=" + testPDF.length + "," + e.getMessage());
        //e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.talend.librariesmanager.deploy.ArtifactsDeployer.java

private void installToRemote(HttpEntity entity, URL targetURL) throws BusinessException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {//from   www  . j  av a  2  s .c o  m
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetURL.getHost(), targetURL.getPort()),
                new UsernamePasswordCredentials(nexusServer.getUserName(), nexusServer.getPassword()));

        HttpPut httpPut = new HttpPut(targetURL.toString());
        httpPut.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPut);
        StatusLine statusLine = response.getStatusLine();
        int responseCode = statusLine.getStatusCode();
        EntityUtils.consume(entity);
        if (responseCode > 399) {
            if (responseCode == 401) {
                throw new BusinessException("Authrity failed");
            } else {
                throw new BusinessException(
                        "Deploy failed: " + responseCode + ' ' + statusLine.getReasonPhrase());
            }
        }
    } catch (Exception e) {
        throw new BusinessException("softwareupdate.error.cannotupload", e.getMessage());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.predic8.membrane.core.rules.SOAPProxy.java

/**
 * @return error or null for success/*from w  ww.j a v a  2 s .co  m*/
 */
private void parseWSDL() throws Exception {
    WSDLParserContext ctx = new WSDLParserContext();
    ctx.setInput(ResolverMap.combine(router.getBaseLocation(), wsdl));
    try {
        WSDLParser wsdlParser = new WSDLParser();
        wsdlParser.setResourceResolver(resolverMap.toExternalResolver().toExternalResolver());

        Definitions definitions = wsdlParser.parse(ctx);

        List<Service> services = definitions.getServices();
        if (services.size() != 1)
            throw new IllegalArgumentException("There are " + services.size()
                    + " services defined in the WSDL, but exactly 1 is required for soapProxy.");
        Service service = services.get(0);

        if (StringUtils.isEmpty(name))
            name = StringUtils.isEmpty(service.getName()) ? definitions.getName() : service.getName();

        List<Port> ports = service.getPorts();
        Port port = selectPort(ports, portName);

        String location = port.getAddress().getLocation();
        if (location == null)
            throw new IllegalArgumentException("In the WSDL, there is no @location defined on the port.");
        try {
            URL url = new URL(location);
            target.setHost(url.getHost());
            if (url.getPort() != -1)
                target.setPort(url.getPort());
            else
                target.setPort(url.getDefaultPort());
            if (key.getPath() == null) {
                key.setUsePathPattern(true);
                key.setPathRegExp(false);
                key.setPath(url.getPath());
            } else {
                targetPath = url.getPath();
            }
            if (location.startsWith("https")) {
                SSLParser sslOutboundParser = new SSLParser();
                target.setSslParser(sslOutboundParser);
            }
            ((ServiceProxyKey) key).setMethod("*");
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("WSDL endpoint location '" + location + "' is not an URL.", e);
        }
        return;
    } catch (Exception e) {
        Throwable f = e;
        while (f.getCause() != null && !(f instanceof ResourceRetrievalException))
            f = f.getCause();
        if (f instanceof ResourceRetrievalException) {
            ResourceRetrievalException rre = (ResourceRetrievalException) f;
            if (rre.getStatus() >= 400)
                throw rre;
            Throwable cause = rre.getCause();
            if (cause != null) {
                if (cause instanceof UnknownHostException)
                    throw (UnknownHostException) cause;
                else if (cause instanceof ConnectException)
                    throw (ConnectException) cause;
            }
        }
        throw new IllegalArgumentException("Could not download the WSDL '" + wsdl + "'.", e);
    }
}

From source file:io.fabric8.api.registry.rules.CamelEndpointFinder.java

protected String switchToUseProxyLink(String uriText) {
    try {/*from   ww  w. jav  a 2s.c  om*/
        URL url = new URL(uriText);
        String host = url.getHost();
        if (Strings.isNotBlank(host)) {
            int port = url.getPort();
            if (port <= 0) {
                port = 80;
            }
            return urlPathJoin("/hawtio/proxy/" + host + "/" + port, url.getPath());
        }
    } catch (MalformedURLException e) {
        LOG.warn("Failed to parse URL " + uriText + ". " + e, e);
    }

    return uriText;
}

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());
        }/*  ww  w  .  ja  va 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.picketbox.http.test.authentication.jetty.DelegatingSecurityFilterHTTPBasicUnitTestCase.java

@Test
public void testBasicAuth() throws Exception {
    URL url = new URL(this.urlStr);

    DefaultHttpClient httpclient = null;

    try {/* w  w w  .  j  a v a  2  s  .  com*/
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(url.toExternalForm());

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(200, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.aludratest.service.gui.web.selenium.TAFMSSeleniumResourceService.java

@Override
public String acquire() {
    // prepare a JSON query to the given TAFMS server
    JSONObject query = new JSONObject();

    try {//  w  w  w  . j av a2 s  . c  o  m
        query.put("resourceType", "selenium");
        query.put("niceLevel", configuration.getIntValue("tafms.niceLevel", 0));
        String jobName = configuration.getStringValue("tafms.jobName");
        if (jobName != null && !"".equals(jobName)) {
            query.put("jobName", jobName);
        }
    } catch (JSONException e) {
    }

    // prepare authentication
    BasicCredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            configuration.getStringValue("tafms.user"), configuration.getStringValue("tafms.password")));

    CloseableHttpClient client = HttpClientBuilder.create()
            .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).disableConnectionState()
            .disableAutomaticRetries().setDefaultCredentialsProvider(provider).build();

    String message = null;
    try {
        boolean wait;

        // use preemptive authentication to avoid double connection count
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        URL url = new URL(getTafmsUrl());
        HttpHost host = new HttpHost(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort(),
                url.getProtocol());
        authCache.put(host, basicAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

        do {
            // send a POST request to resource URL
            HttpPost request = new HttpPost(getTafmsUrl() + "resource");

            // attach query as JSON string data
            request.setEntity(new StringEntity(query.toString(), ContentType.APPLICATION_JSON));

            CloseableHttpResponse response = null;

            // fire request
            response = client.execute(request, localcontext);

            try {
                if (response.getStatusLine() == null) {
                    throw new ClientProtocolException("No HTTP status line transmitted");
                }

                message = extractMessage(response);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    LOG.error("Exception when querying TAFMS server for resource. HTTP Status: "
                            + response.getStatusLine().getStatusCode() + ", message: " + message);
                    return null;
                }

                JSONObject object = new JSONObject(message);
                if (object.has("errorMessage")) {
                    LOG.error("TAFMS server reported an error: " + object.get("errorMessage"));
                    return null;
                }

                // continue wait?
                if (object.has("waiting") && object.getBoolean("waiting")) {
                    wait = true;
                    query.put("requestId", object.getString("requestId"));
                } else {
                    JSONObject resource = object.optJSONObject("resource");
                    if (resource == null) {
                        LOG.error("TAFMS server response did not provide a resource. Message was: " + message);
                        return null;
                    }

                    String sUrl = resource.getString("url");
                    hostResourceIds.put(sUrl, object.getString("requestId"));

                    return sUrl;
                }
            } finally {
                IOUtils.closeQuietly(response);
            }
        } while (wait);

        // should never come here
        return null;
    } catch (ClientProtocolException e) {
        LOG.error("Exception in HTTP transmission", e);
        return null;
    } catch (IOException e) {
        LOG.error("Exception in communication with TAFMS server", e);
        return null;
    } catch (JSONException e) {
        LOG.error("Invalid JSON received from TAFMS server. JSON message was: " + message, e);
        return null;
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.appeligo.search.actions.ToolbarUpdateAction.java

public String execute() throws Exception {
    Integer toolbarRevision = (Integer) getSession().get("toolbarRevision");
    if (toolbarRevision == null) {
        revision = 0;//  ww  w  . ja v  a  2s  .c  o  m
    } else {
        revision = toolbarRevision.intValue() + 1;
    }
    getSession().put("toolbarRevision", new Integer(revision));
    try {
        URL u = new URL(url);
        String host = u.getHost();
        if (host.startsWith("www.")) {
            host = host.substring(4);
        }
        log.debug(host);
        log.debug(u.getPort());
        log.debug(u.getPath());
        SearchEngine searchEngine = searchEngineMap.get(host);
        if ((searchEngine != null)
                && (u.getPort() == searchEngine.getPort()
                        || ((u.getPort() == -1) && (searchEngine.getPort() == 80)))
                && (u.getPath().indexOf(searchEngine.getPath()) == 0)) {
            String query = u.getQuery();
            if (query != null) {
                String[] params = query.split("&");
                for (String param : params) {
                    if (param.startsWith(searchEngine.getParam())) {
                        log.debug(param);
                        String q = param.substring(searchEngine.getParam().length());
                        q = URLDecoder.decode(q, "UTF-8");
                        log.debug(q);
                        setQuery(q);
                        String indexDir = ConfigUtils.getSystemConfig().getString("luceneIndex");
                        String compositeIndexDir = ConfigUtils.getSystemConfig().getString("compositeIndex");
                        if (IndexReader.indexExists(indexDir)) {
                            String lineup = getLineup();
                            searchResults = new SearchResults(indexDir, compositeIndexDir, 10, lineup);
                            searchResults.setLineup(lineup);
                            searchResults.setQuery(getQuery());
                            searchResults.setSearchType(getSearchTypeAsSearchType());
                            hits = searchResults.getSearchResults(0);
                        }
                        break;
                    }
                }
            }
        }
    } catch (MalformedURLException e) {
        //ignore;
    }

    return SUCCESS;
}

From source file:at.gv.egiz.pdfas.web.servlets.ErrorPage.java

protected void process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (PdfAsHelper.getFromDataUrl(request)) {
        // redirect to here!
        response.sendRedirect(PdfAsHelper.generateErrorURL(request, response));
        return;/*w ww . j a  v a  2  s . co  m*/
    } else {
        String errorURL = PdfAsHelper.getErrorURL(request, response);
        Throwable e = PdfAsHelper.getSessionException(request, response);

        StatisticEvent statisticEvent = PdfAsHelper.getStatisticEvent(request, response);
        if (statisticEvent != null) {
            if (!statisticEvent.isLogged()) {
                statisticEvent.setStatus(Status.ERROR);
                statisticEvent.setException(e);
                if (e instanceof PDFASError) {
                    statisticEvent.setErrorCode(((PDFASError) e).getCode());
                }
                statisticEvent.setEndNow();
                statisticEvent.setTimestampNow();
                StatisticFrontend.getInstance().storeEvent(statisticEvent);
                statisticEvent.setLogged(true);
            }
        }

        String message = PdfAsHelper.getSessionErrMessage(request, response);
        if (errorURL != null && WebConfiguration.isProvidePdfURLinWhitelist(errorURL)) {
            String template = PdfAsHelper.getErrorRedirectTemplateSL();

            URL url = new URL(errorURL);
            String errorURLProcessed = url.getProtocol() + "://" + // "http" + "://
                    url.getHost() + // "myhost"
                    ":" + // ":"
                    url.getPort() + // "8080"
                    url.getPath();

            template = template.replace("##ERROR_URL##", errorURLProcessed);

            String extraParams = UrlParameterExtractor.buildParameterFormString(url);
            template = template.replace("##ADD_PARAMS##", extraParams);

            String target = PdfAsHelper.getInvokeTarget(request, response);

            if (target == null) {
                target = "_self";
            }

            template = template.replace("##TARGET##", StringEscapeUtils.escapeHtml4(target));

            if (e != null && WebConfiguration.isShowErrorDetails()) {
                template = template.replace("##CAUSE##", URLEncoder.encode(e.getMessage(), "UTF-8"));
            } else {
                template = template.replace("##CAUSE##", "");
            }
            if (message != null) {
                template = template.replace("##ERROR##", URLEncoder.encode(message, "UTF-8"));
            } else {
                template = template.replace("##ERROR##", "Unbekannter Fehler");
            }
            response.setContentType("text/html");
            response.getWriter().write(template);
            response.getWriter().close();
        } else {
            if (errorURL != null) {
                logger.warn(errorURL + " is not allowed by whitelist");
            }

            String template = PdfAsHelper.getErrorTemplate();
            if (message != null) {
                template = template.replace(ERROR_MESSAGE, message);
            } else {
                template = template.replace(ERROR_MESSAGE, "Unbekannter Fehler");
            }

            if (e != null && WebConfiguration.isShowErrorDetails()) {
                template = template.replace(ERROR_STACK, HTMLFormater.formatStackTrace(e.getStackTrace()));
            } else {
                template = template.replace(ERROR_STACK, "");
            }

            response.setContentType("text/html");
            response.getWriter().write(template);
            response.getWriter().close();
        }
    }
}

From source file:eu.markov.jenkins.plugin.mvnmeta.MavenMetadataParameterDefinitionBackwardCompatibility.java

private String createRepoBaseUrlWithImplicitUser() throws MalformedURLException {
    StringBuilder credentialsIdBuilder = new StringBuilder();

    URL url = new URL(this.getRepoBaseUrl());

    credentialsIdBuilder.append(url.getProtocol());
    credentialsIdBuilder.append("://");
    credentialsIdBuilder.append(this.username);
    credentialsIdBuilder.append("@");
    credentialsIdBuilder.append(url.getHost());

    int port = url.getPort();
    if (port > -1) {
        credentialsIdBuilder.append(":");
        credentialsIdBuilder.append(port);
    }/*from  w w  w  . ja  va2 s .c o m*/

    credentialsIdBuilder.append(url.getPath());

    return credentialsIdBuilder.toString();
}