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:com.twinsoft.convertigo.engine.util.WsReference.java

private static void tryAuthentication(RemoteFileReference wsReference) throws Exception {
    URL urlToConnect = wsReference.getUrl();
    String wsdlUrl = wsReference.getUrlpath();
    String username = wsReference.getAuthUser();
    String password = wsReference.getAuthPassword();

    HttpClient client = new HttpClient();

    client.getState().setCredentials(new AuthScope(urlToConnect.getHost(), urlToConnect.getPort()),
            new UsernamePasswordCredentials(username, password));

    GetMethod get = new GetMethod(wsdlUrl);
    get.setDoAuthentication(true);/*ww  w .  j a  v  a2  s.c  o  m*/

    int statuscode = client.executeMethod(get);

    if (statuscode == HttpStatus.SC_UNAUTHORIZED) {
        throw new Exception(HttpStatus.SC_UNAUTHORIZED + " - Unauthorized connection!");
    }
}

From source file:com.predic8.membrane.core.interceptor.apimanagement.apiconfig.EtcdRegistryApiConfig.java

public void initAmc() {
    String workingDir = ((BaseLocationApplicationContext) context).getBaseLocation();
    String etcdUrlForAmc = null;//w ww.ja v a  2 s.  co m
    URL u = null;
    try {
        u = new URL(getUrl());

    } catch (MalformedURLException e) {
        try {
            u = new URL("http://" + getUrl());
        } catch (MalformedURLException ignored) {
        }
    }
    if (u == null) {
        log.error("Url malformed: " + getUrl());
    }
    etcdUrlForAmc = "etcd://" + u.getHost() + ":" + u.getPort();
    amc = new ApiManagementConfiguration(workingDir, etcdUrlForAmc, membraneId);
}

From source file:org.apache.juddi.v3.client.mapping.wsdl.WSDLLocatorImpl.java

private InputSource getImportFromUrl(String url) {
    InputSource inputSource = null;
    DefaultHttpClient httpclient = null;
    try {/*from w w  w  .  j a v a 2  s  .c o  m*/
        URL url2 = new URL(url);
        if (!url.toLowerCase().startsWith("http")) {
            return getImportFromFile(url);
        }
        boolean usessl = false;
        int port = 80;
        if (url.toLowerCase().startsWith("https://")) {
            port = 443;
            usessl = true;
        }

        if (url2.getPort() > 0) {
            port = url2.getPort();
        }

        if (ignoreSSLErrors && usessl) {
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("https", port, new MockSSLSocketFactory()));
            ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
            httpclient = new DefaultHttpClient(cm);
        } else {
            httpclient = new DefaultHttpClient();
        }

        if (username != null && username.length() > 0 && password != null && password.length() > 0) {

            httpclient.getCredentialsProvider().setCredentials(new AuthScope(url2.getHost(), port),
                    new UsernamePasswordCredentials(username, password));
        }
        HttpGet httpGet = new HttpGet(url);
        try {

            HttpResponse response1 = httpclient.execute(httpGet);
            //System.out.println(response1.getStatusLine());
            // HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String handleResponse = responseHandler.handleResponse(response1);
            StringReader sr = new StringReader(handleResponse);
            inputSource = new InputSource(sr);

        } finally {
            httpGet.releaseConnection();

        }

        //  InputStream inputStream = importUrl.openStream();
        //inputSource = new InputSource(inputStream);
        latestImportURI = url;
    } catch (Exception e) {
        log.error(e.getMessage());
        log.debug(e.getMessage(), e);
        lastException = e;
    } finally {
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
    }
    return inputSource;
}

From source file:com.funambol.email.engine.source.EmailGeneric.java

/**
 * Retrieve the Content Provider URL from the Email SynSource configuration
 * or from the SereverURI configuration/*www . j  a  v a  2  s  .  c om*/
 * @return The Content Provider URL
 */
protected String getContentProviderURL() {
    String attachProviderUrl = ess.getContentProviderURL();
    if (StringUtils.isBlank(attachProviderUrl)) {
        Configuration config = Configuration.getConfiguration();
        String serverURI = config.getServerConfig().getEngineConfiguration().getServerURI();
        if (StringUtils.isBlank(serverURI)) {
            attachProviderUrl = ContentProviderInfo.CONTENT_PROVIDER_PATH;
        } else {
            try {
                URL baseUrl = new URL(serverURI);
                attachProviderUrl = new URL(baseUrl.getProtocol(), baseUrl.getHost(), baseUrl.getPort(),
                        ContentProviderInfo.CONTENT_PROVIDER_PATH).toString();
            } catch (MalformedURLException ex) {
                log.error("Invalid Server URI", ex);
                attachProviderUrl = ContentProviderInfo.CONTENT_PROVIDER_PATH;
            }
        }
    }
    return attachProviderUrl;
}

From source file:org.aludratest.cloud.selenium.impl.SeleniumHttpProxy.java

private void checkState() {
    // first of all, check if the resource is idle for too long. Regain it then.
    if (resource.getState() == ResourceState.IN_USE && resource.getIdleTime() > maxIdleTime) {
        // try to safely shutdown Selenium session
        LOG.info("Detected IDLE IN_USE resource (" + resource.getOriginalUrl() + "), trying to regain it.");
        resource.tryKillSession();//from  www  .  j a  va2  s.co  m
        resource.stopUsing();
        return;
    }

    // check state via our very own proxy - to get custom timeouts and direct feedback for lost connections.
    InputStream in = null;
    HttpGet request = null;
    CloseableHttpResponse response = null;
    try {
        URL uurl = new URL(accessUrl);
        URL checkUrl = new URL("http://127.0.0.1:" + uurl.getPort() + uurl.getPath() + "/wd/hub/status");
        LOG.debug("Checking health state for " + resource.getOriginalUrl() + " using "
                + checkUrl.toExternalForm());

        request = new HttpGet(checkUrl.toURI());
        response = healthCheckClient.execute(request);

        if (response.getStatusLine() != null
                && response.getStatusLine().getStatusCode() == HttpServletResponse.SC_GATEWAY_TIMEOUT) {
            LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (proxy timeout)");
            resource.setState(ResourceState.DISCONNECTED);
        } else if (response.getStatusLine() != null
                && response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
            LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (invalid HTTP status code "
                    + response.getStatusLine().getStatusCode() + ")");
            resource.setState(ResourceState.DISCONNECTED);
        } else if (response.getEntity() != null) {
            in = response.getEntity().getContent();
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            IOUtils.copy(in, buf);
            String statusStr = new String(buf.toByteArray(), "UTF-8");
            if (statusStr.contains("\"status\":0")) {
                if (resource.getState() == ResourceState.DISCONNECTED
                        || resource.getState() == ResourceState.CONNECTED) {
                    resource.setState(ResourceState.READY);
                    LOG.debug(resource.getOriginalUrl() + " is READY");
                }
            } else {
                LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (invalid response content: " + statusStr
                        + ")");
                resource.setState(ResourceState.DISCONNECTED);
            }
        } else {
            LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED (invalid or no HTTP response)");
            resource.setState(ResourceState.DISCONNECTED);
        }
    } catch (IOException e) {
        LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED due to IOException: " + e.getMessage());
        resource.setState(ResourceState.DISCONNECTED);
    } catch (URISyntaxException e) {
        LOG.debug(resource.getOriginalUrl() + " is DISCONNECTED due to URISyntaxException: " + e.getMessage());
        resource.setState(ResourceState.DISCONNECTED);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(response);
    }
}

From source file:com.twinsoft.convertigo.beans.steps.SequenceStep.java

protected void prepareForRequestable(Context javascriptContext, Scriptable scope)
        throws MalformedURLException, EngineException {
    Sequence targetSequence = getTargetSequence();

    if (Engine.isStudioMode()) {
        if (targetSequence != null) {
            if (sequence.getOriginal().equals(targetSequence.getOriginal())) {
                throw new EngineException("Execution of recursive sequence is not allowed in Studio mode!");
            }//from w w  w.  j  a  va  2  s . c om
        }
    }

    String ctxName = getContextName(javascriptContext, scope);
    boolean useSequenceJSession = sequence.useSameJSessionForSteps();
    boolean maintainContext = useSequenceJSession && !ctxName.startsWith("Container-");
    boolean maintainSession = useSequenceJSession;

    boolean inheritContex = inheritTransactionCtx && sequence.equals(getTransactionContextMaintainer());
    String inheritedCxtName = sequence.getInheritedContextName();
    inheritedCxtName = (inheritContex && (inheritedCxtName == null)) ? sequence.getContextName()
            : inheritedCxtName;
    inheritedCxtName = (inheritedCxtName == null) ? "" : inheritedCxtName;

    if (isInternalInvoke()) {
        request.put(Parameter.Project.getName(), new String[] { projectName });
        request.put(Parameter.MotherSequenceContext.getName(), new String[] { sequence.context.contextID });
        request.put(Parameter.Sequence.getName(), new String[] { targetSequence.getName() });
        request.put(Parameter.Context.getName(), new String[] { sequence.addStepContextName(ctxName) });
        request.put(Parameter.SequenceInheritedTransactionContext.getName(),
                inheritContex ? new String[] { inheritedCxtName } : new String[] { "" });
        if (!maintainContext)
            request.put(Parameter.RemoveContext.getName(), new String[] { "" });
        if (!maintainSession)
            request.put(Parameter.RemoveSession.getName(), new String[] { "" });
        getPostQuery(scope);
    } else {
        targetUrl = EnginePropertiesManager.getProperty(PropertyName.APPLICATION_SERVER_CONVERTIGO_URL);
        targetUrl += "/projects/" + projectName + "/.xml?";

        URL url = new URL(targetUrl);
        String host = url.getHost();
        int port = url.getPort();

        Engine.logBeans.trace("(SequenceStep) Host: " + host + ":" + port);
        hostConfiguration.setHost(host, port);

        // Retrieves new HttpState!!
        // This will force a new http session on convertigo server : new context for sequence
        httpState = sequence.getNewHttpState();

        method = new PostMethod(targetUrl);
        method.setRequestHeader("Content-Type", MimeType.WwwForm.value());

        // Set transaction sessionId from context maintainer
        String sessionId = getTransactionSessionId();
        if (useSequenceJSession) {
            Engine.logBeans.trace("(SequenceStep) JSESSIONID required : " + sessionId);
            if (sessionId != null) {
                method.setRequestHeader("Cookie", "JSESSIONID=" + sessionId + ";");
                Engine.logBeans.trace("(SequenceStep) JSESSIONID used : " + sessionId);
            } else {
                Engine.logBeans.trace("(SequenceStep) JSESSIONID is null");
            }
        } else {
            if (sessionId != null) {
                method.addRequestHeader("Transaction-JSessionId", sessionId);
                Engine.logBeans.trace("(SequenceStep) Transaction JSESSIONID used : " + sessionId);
            } else {
                Engine.logBeans.trace("(SequenceStep) Transaction JSESSIONID is null");
            }
        }

        String postQuery = getPostQuery(scope);
        if (!maintainContext && (postQuery.indexOf(Parameter.RemoveContext.getName()) == -1))
            postQuery = addParamToPostQuery(Parameter.RemoveContext.getName(), "", postQuery);
        if (!maintainSession && (postQuery.indexOf(Parameter.RemoveSession.getName()) == -1))
            postQuery = addParamToPostQuery(Parameter.RemoveSession.getName(), "", postQuery);
        if (postQuery.indexOf(Parameter.SequenceInheritedTransactionContext.getName()) == -1)
            postQuery = addParamToPostQuery(Parameter.SequenceInheritedTransactionContext.getName(),
                    inheritContex ? inheritedCxtName : "", postQuery);
        if (postQuery.indexOf(Parameter.Sequence.getName()) == -1)
            postQuery = addParamToPostQuery(Parameter.Sequence.getName(), targetSequence.getName(), postQuery);
        if (postQuery.indexOf(Parameter.Context.getName()) == -1)
            postQuery = addParamToPostQuery(Parameter.Context.getName(), sequence.addStepContextName(ctxName),
                    postQuery);
        if (postQuery.indexOf(Parameter.MotherSequenceContext.getName()) == -1)
            postQuery = addParamToPostQuery(Parameter.MotherSequenceContext.getName(),
                    sequence.context.contextID, postQuery);

        if (Engine.logBeans.isTraceEnabled())
            Engine.logBeans.trace(
                    "(SequenceStep) postQuery :" + Visibility.Logs.replaceVariables(getVariables(), postQuery));

        try {
            method.setRequestEntity(new StringRequestEntity(postQuery, null, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new EngineException("Encoding error", e);
        }
    }
}

From source file:org.gvnix.service.roo.addon.addon.security.SecurityServiceImpl.java

/**
 * Get certificates in the chain of the host server and import them.
 * <p>/*from w ww  . j av a 2 s .  c  o m*/
 * Tries to get the certificates in the certificates chain of the host
 * server and import them to:
 * <ol>
 * <li>A custom keystore in <code>SRC_MAIN_RESOURCES/gvnix-cacerts</code></li>
 * <li>The JVM cacerts keystore in
 * <code>$JAVA_HOME/jre/lib/security/cacerts</code>. Here we can have a
 * problem if JVM <code>cacerts</code> file is not writable by the user due
 * to file permissions. In this case we throw an exception informing about
 * the error.</li>
 * </ol>
 * </p>
 * <p>
 * With that operation we can try again to get the WSDL.<br/>
 * Also it exports the chain certificates to <code>.cer</code> files in
 * <code>SRC_MAIN_RESOURCES</code>, so the developer can distribute them for
 * its installation in other environments or just in case we reach the
 * problem with the JVM <code>cacerts</code> file permissions.
 * </p>
 * 
 * @see GvNix509TrustManager#saveCertFile(String, X509Certificate,
 *      FileManager, PathResolver)
 * @see <a href=
 *      "http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html"
 *      >Java SE keytool</a>.
 */
protected Document installCertificates(String loc, String pass)
        throws NoSuchAlgorithmException, KeyStoreException, Exception, KeyManagementException,
        MalformedURLException, IOException, UnknownHostException, SocketException, SAXException {

    // Create a SSL context
    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    // Passphrase of the keystore: "changeit" by default
    char[] passArray = (StringUtils.isNotBlank(pass) ? pass.toCharArray() : "changeit".toCharArray());

    // Get the project keystore and copy it from JVM if not exists
    File keystore = getProjectKeystore();

    tmf.init(GvNix509TrustManager.loadKeyStore(keystore, passArray));

    X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    GvNix509TrustManager tm = new GvNix509TrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory factory = context.getSocketFactory();

    // Open URL location (default 443 port if not defined)
    URL url = new URL(loc);
    String host = url.getHost();
    int port = url.getPort() == -1 ? 443 : url.getPort();
    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
    socket.setSoTimeout(10000);

    Document doc = null;
    try {

        socket.startHandshake();
        URLConnection connection = url.openConnection();
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(factory);
        }

        doc = XmlUtils.getDocumentBuilder().parse(connection.getInputStream());

        socket.close();

    } catch (SSLException ssle) {

        // Get needed certificates for this host
        getCerts(tm, host, keystore, passArray);
        doc = getWsdl(loc, pass);

    } catch (IOException ioe) {

        invalidHostCert(passArray, keystore, tm, host);
    }

    Validate.notNull(doc, "No valid document format");
    return doc;
}

From source file:com.alu.e3.gateway.loadbalancer.E3HttpClientConfigurer.java

/**
 * Converts a TargetHost to an HttpRoute 
 * @param targetHost the target host to transform
 * @return HttpRoute HTTP route//w w w.j av  a 2 s  .  c  o  m
 * @throws MalformedURLException
 */
private HttpRoute getHttpRoute(TargetHost targetHost) throws MalformedURLException {

    HttpRoute route = null;

    URL url = new URL(targetHost.getUrl());

    boolean secured = url.getProtocol().equalsIgnoreCase(HTTP_SECURED_PROTOCOL);

    if (forwardProxy != null) {

        Integer proxyPort = Integer.parseInt(forwardProxy.getProxyPort());
        String proxyHost = forwardProxy.getProxyHost();

        route = new HttpRoute(new HttpHost(url.getHost(), url.getPort()), null,
                new HttpHost(proxyHost, proxyPort), secured);
    } else {

        route = new HttpRoute(new HttpHost(url.getHost(), url.getPort()), null, secured);
    }

    return route;
}

From source file:org.alfresco.maven.plugin.AbstractRefreshWebappMojo.java

/**
 * Helper method to make a POST request to the Alfresco Webapp
 *
 * @param alfrescoTomcatUrl the URL for the webapp we want to post to
 * @param postData the POST data that should be sent
 * @param operation information about the operation we are performing
 *//*from w  ww  . j a v a2s  .  c om*/
private void makePostCall(URL alfrescoTomcatUrl, List<NameValuePair> postData, String operation) {
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    try {
        // Set up a HTTP POST request to the Alfresco Webapp we are targeting
        HttpHost targetHost = new HttpHost(alfrescoTomcatUrl.getHost(), alfrescoTomcatUrl.getPort(),
                alfrescoTomcatUrl.getProtocol());

        // Set up authentication parameters
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(refreshUsername, refreshPassword));

        // Create the HTTP Client we will use to make the call
        client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

        // 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
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        // Make the call to Refresh the Alfresco Webapp
        HttpPost httpPost = new HttpPost(alfrescoTomcatUrl.toURI());
        response = client.execute(httpPost);
        if (postData != null) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8");
            httpPost.setEntity(entity);
        }
        httpPost.setHeader("Accept-Charset", "iso-8859-1,utf-8");
        httpPost.setHeader("Accept-Language", "en-us");
        response = client.execute(httpPost);

        // If no response, no method has been passed
        if (response == null) {
            getLog().error("POST request failed to " + alfrescoTomcatUrl.toString() + ", " + getAbortedMsg());
            return;
        }

        // Check if we got a successful response or not
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            getLog().info("Successfull " + operation + " for " + refreshWebappName);
        } else {
            String reasonPhrase = response.getStatusLine().getReasonPhrase();
            getLog().warn("Failed to " + operation + " for " + refreshWebappName + ". Response status: "
                    + statusCode + ", message: " + reasonPhrase);
        }
    } catch (Exception ex) {
        getLog().error("POST request failed to " + alfrescoTomcatUrl.toString() + ", " + getAbortedMsg());
        getLog().error("Exception Msg: " + ex.getMessage());
    } finally {
        closeQuietly(response);
        closeQuietly(client);
    }
}