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:io.selendroid.server.grid.SelfRegisteringRemote.java

/**
 * Extracts the configuration.// w  w  w.  jav a2  s. co  m
 * 
 * @return The configuration
 * @throws JSONException On JSON errors.
 */
private JSONObject getConfiguration() throws JSONException {
    JSONObject configuration = new JSONObject();

    configuration.put("port", config.getPort());
    configuration.put("register", true);

    if (config.getProxy() != null) {
        configuration.put("proxy", config.getProxy());
    } else {
        configuration.put("proxy", "org.openqa.grid.selenium.proxy.DefaultRemoteProxy");
    }
    configuration.put("role", "node");
    configuration.put("registerCycle", 5000);
    configuration.put("maxInstances", 5);

    // adding hub details
    URL registrationUrl;
    try {
        registrationUrl = new URL(config.getRegistrationUrl());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        throw new SelendroidException("Grid hub url cannot be parsed: " + e.getMessage());
    }
    configuration.put("hubHost", registrationUrl.getHost());
    configuration.put("hubPort", registrationUrl.getPort());

    // adding driver details
    configuration.put("remoteHost", "http://" + config.getServerHost() + ":" + config.getPort());
    return configuration;
}

From source file:client.ui.Container.java

private JSONObject getCert(SocketFactory factory, URL url) {
    JSONObject json = new JSONObject();
    json.put("host", url.getHost());
    json.put("port", url.getPort());

    try {/*from  w  w w  .j a  v  a2  s .  c o m*/
        log("Get Certs: " + url.getHost() + ":" + url.getPort());

        SSLSocket socket = (SSLSocket) factory.createSocket(url.getHost(), url.getPort());
        socket.startHandshake();

        Certificate[] certs = socket.getSession().getPeerCertificates();
        String result = "";

        for (Certificate cert : certs) {

            if (cert instanceof X509Certificate) {
                try {
                    ((X509Certificate) cert).checkValidity();
                    result += "OK ";

                } catch (CertificateExpiredException cee) {
                    result += "Expired ";
                } catch (CertificateNotYetValidException ex) {
                    result += "NotYetValid ";
                }
            }
        }

        log("Result: " + result.trim());
        json.put("result", result.trim());

    } catch (SSLException se) {
        log("Error: SSLException (" + se.getMessage() + ")");
        json.put("result", "SSLException: " + se.getMessage());
    } catch (ConnectException ce) {
        log("Error: ConnectException (" + ce.getMessage() + ")");
        json.put("result", "ConnectException: " + ce.getMessage());
    } catch (IOException ioe) {
        log("Error: IOException (" + ioe.getMessage() + ")");
        json.put("result", "IOException: " + ioe.getMessage());
    }

    return json;
}

From source file:au.edu.usq.fascinator.harvester.fedora.FedoraHarvester.java

/**
 * Initialisation of Fedora Harvester plugin
 * //from  w ww . jav a  2s  .com
 * @throws HarvesterException if fails to initialise
 */
@Override
public void init() throws HarvesterException {
    JsonConfigHelper config;

    // Read config
    try {
        config = new JsonConfigHelper(getJsonConfig().toString());
    } catch (IOException ex) {
        throw new HarvesterException("Failed reading configuration", ex);
    }

    baseUrl = config.get("harvester/fedora/baseUrl");
    maxRequests = Integer.parseInt(config.get("harvester/fedora/maxRequests"));
    requestSize = DEFAULT_REQUEST_SIZE;
    if (config.get("harvester/fedora/requestSize") != null) {
        requestSize = Integer.parseInt(config.get("harvester/fedora/requestSize"));
    }

    if (baseUrl != null) {
        restClient = new FedoraRestClient(baseUrl);
    } else {
        throw new HarvesterException("Fedora baseUrl is not set");
    }

    searchFiles = new LinkedList<File>();
    started = false;
    searchTerms = "*";
    URL u;
    try {
        u = new URL(baseUrl);
        String tmpDir = System.getProperty("java.io.tmpdir");
        String tmpName = u.getHost() + "_" + u.getPort();
        workDir = new File(tmpDir, tmpName);
        workDir.mkdirs();
        try {
            jc = JAXBContext.newInstance(ResultType.class);
            um = jc.createUnmarshaller();
        } catch (JAXBException jaxbe) {
            throw new HarvesterException(jaxbe.getMessage());
        }
    } catch (MalformedURLException e) {
        throw new HarvesterException("Malformed baseUrl: " + baseUrl, e);
    }

    //For now assume since is null....
    Date since = null;
    getItems(since);
}

From source file:com.cladonia.xngreditor.URLUtilities.java

/**
 * Returns a String representation without the Username and Password.
 * /*from  w w  w.  j  a va2s  . c o m*/
 * @param url the url to convert to a String...
 * 
 * @return the string representation.
 */
public static String toString(URL url) {
    if (url != null) {
        StringBuffer result = new StringBuffer(url.getProtocol());
        result.append(":");

        if (url.getHost() != null && url.getHost().length() > 0) {
            result.append("//");
            result.append(url.getHost());
        }

        if (url.getPort() > 0) {
            result.append(":");
            result.append(url.getPort());
        }

        if (url.getPath() != null) {
            result.append(url.getPath());
        }

        if (url.getQuery() != null) {
            result.append('?');
            result.append(url.getQuery());
        }

        if (url.getRef() != null) {
            result.append("#");
            result.append(url.getRef());
        }

        return result.toString();
    }

    return null;
}

From source file:org.smssecure.smssecure.mms.LegacyMmsConnection.java

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
        credsProvider.setCredentials(/*from ww  w . j a  v  a 2  s .  c o  m*/
                new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }

    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setUserAgent(SilencePreferences.getMmsUserAgent(context, USER_AGENT))
            .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();
}

From source file:wsattacker.plugin.intelligentdos.requestSender.Http4RequestSenderImpl.java

public String sendRequestHttpClient(RequestObject requestObject) {
    String strUrl = requestObject.getEndpoint();
    String strXml = requestObject.getRequestContent();

    StringBuilder result = new StringBuilder();
    BufferedReader rd = null;//w  w w .j av a 2 s  .c o m
    try {
        URL url = new URL(strUrl);
        String protocol = url.getProtocol();

        HttpClient client;
        if (protocol.equalsIgnoreCase("https")) {
            SSLSocketFactory sf = get();
            Scheme httpsScheme = new Scheme("https", url.getPort(), sf);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(httpsScheme);

            // apache HttpClient version >4.2 should use
            // BasicClientConnectionManager
            ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);

            client = new DefaultHttpClient(cm);
        } else {
            client = new DefaultHttpClient();
        }

        setParamsToClient(client);

        HttpPost post = new HttpPost(strUrl);
        setHeader(requestObject, post);

        ByteArrayEntity entity = new ByteArrayEntity(strXml.getBytes("UTF-8")) {
            @Override
            public void writeTo(OutputStream outstream) throws IOException {
                super.writeTo(outstream);
                sendLastByte = System.nanoTime();
            }
        };

        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        receiveFirstByte = System.nanoTime();

        rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), Charset.defaultCharset()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (IOException e) {
        return e.getMessage();
    } catch (RuntimeException e) {
        return e.getMessage();
    } finally {
        if (rd != null) {
            try {
                rd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return result.toString();
}

From source file:org.opencastproject.workflow.handler.MediaPackagePostOperationHandler.java

/**
 * {@inheritDoc}/* w w w  .j a v a2 s . c  o  m*/
 *
 * @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance,
 *      JobContext)
 */
public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context)
        throws WorkflowOperationException {

    // get configuration
    WorkflowOperationInstance currentOperation = workflowInstance.getCurrentOperation();
    Configuration config = new Configuration(currentOperation);

    MediaPackage mp = workflowInstance.getMediaPackage();

    /* Check if we need to replace the Mediapackage we got with the published
     * Mediapackage from the Search Service */
    if (config.mpFromSearch()) {
        SearchQuery searchQuery = new SearchQuery();
        searchQuery.withId(mp.getIdentifier().toString());
        SearchResult result = searchService.getByQuery(searchQuery);
        if (result.size() != 1) {
            throw new WorkflowOperationException("Received multiple results for identifier" + "\""
                    + mp.getIdentifier().toString() + "\" from search service. ");
        }
        logger.info("Getting Mediapackage from Search Service");
        mp = result.getItems()[0].getMediaPackage();
    }

    logger.info("Submitting \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") as "
            + config.getFormat().name() + " to " + config.getUrl().toString());

    try {
        // serialize MediaPackage to target format
        String mpStr;
        if (config.getFormat() == Configuration.Format.JSON) {
            mpStr = MediaPackageParser.getAsJSON(mp);
        } else {
            mpStr = MediaPackageParser.getAsXml(mp);
        }

        // Log mediapackge
        if (config.debug()) {
            logger.info(mpStr);
        }

        // constrcut message body
        List<NameValuePair> data = new ArrayList<NameValuePair>();
        data.add(new BasicNameValuePair("mediapackage", mpStr));
        data.addAll(config.getAdditionalFields());

        // construct POST
        HttpPost post = new HttpPost(config.getUrl());
        post.setEntity(new UrlEncodedFormEntity(data, config.getEncoding()));

        // execute POST
        DefaultHttpClient client = new DefaultHttpClient();

        // Handle authentication
        if (config.authenticate()) {
            URL targetUrl = config.getUrl().toURL();
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(targetUrl.getHost(), targetUrl.getPort()), config.getCredentials());
        }

        HttpResponse response = client.execute(post);

        // throw Exception if target host did not return 200
        int status = response.getStatusLine().getStatusCode();
        if ((status >= 200) && (status < 300)) {
            if (config.debug()) {
                logger.info("Successfully submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString()
                        + ") to " + config.getUrl().toString() + ": " + status);
            }
        } else if (status == 418) {
            logger.warn("Submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") to "
                    + config.getUrl().toString() + ": The target claims to be a teapot. "
                    + "The Reason for this is probably an insane programmer.");
        } else {
            throw new WorkflowOperationException(
                    "Faild to submit \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + "), "
                            + config.getUrl().toString() + " answered with: " + Integer.toString(status));
        }
    } catch (Exception e) {
        if (e instanceof WorkflowOperationException) {
            throw (WorkflowOperationException) e;
        } else {
            logger.error("Submitting mediapackage failed: {}", e.toString());
            throw new WorkflowOperationException(e);
        }
    }
    return createResult(mp, Action.CONTINUE);
}

From source file:ed.net.CookieJar.java

/**
 * Performs RFC 2109 {@link Cookie} validation
 * /*from   w w  w.  j a v a 2 s.co m*/
 * @param url the source of the cookie
 * @param cookie The cookie to validate.
 * @throws IllegalArgumentException if an exception occurs during validation
 */
private void validate(URL url, Cookie cookie) {
    String host = url.getHost();
    int port = url.getPort();
    String path = url.getPath();

    // based on org.apache.commons.httpclient.cookie.CookieSpecBase
    if (host == null) {
        throw new IllegalArgumentException("Host of origin may not be null");
    }
    if (host.trim().equals("")) {
        throw new IllegalArgumentException("Host of origin may not be blank");
    }
    if (port < 0)
        port = 80;

    if (path == null) {
        throw new IllegalArgumentException("Path of origin may not be null.");
    }
    if (path.trim().equals("")) {
        path = "/";
    }
    host = host.toLowerCase();
    // check version
    if (cookie.getVersion() < 0) {
        throw new MalformedCookieException("Illegal version number " + cookie.getValue());
    }

    // security check... we musn't allow the server to give us an
    // invalid domain scope

    // Validate the cookies domain attribute. NOTE: Domains without
    // any dots are allowed to support hosts on private LANs that don't
    // have DNS names. Since they have no dots, to domain-match the
    // request-host and domain must be identical for the cookie to sent
    // back to the origin-server.
    if (host.indexOf(".") >= 0) {
        // Not required to have at least two dots. RFC 2965.
        // A Set-Cookie2 with Domain=ajax.com will be accepted.

        // domain must match host
        if (!host.endsWith(cookie.getDomain())) {
            String s = cookie.getDomain();
            if (s.startsWith(".")) {
                s = s.substring(1, s.length());
            }
            if (!host.equals(s)) {
                throw new MalformedCookieException("Illegal domain attribute \"" + cookie.getDomain()
                        + "\". Domain of origin: \"" + host + "\"");
            }
        }
    } else {
        if (!host.equals(cookie.getDomain())) {
            throw new MalformedCookieException("Illegal domain attribute \"" + cookie.getDomain()
                    + "\". Domain of origin: \"" + host + "\"");
        }
    }

    // another security check... we musn't allow the server to give us a
    // cookie that doesn't match this path
    if (!path.startsWith(cookie.getPath())) {
        throw new MalformedCookieException(
                "Illegal path attribute \"" + cookie.getPath() + "\". Path of origin: \"" + path + "\"");
    }

    // Validate using RFC 2109
    // --------------------------------------------------------
    if (cookie.getName().indexOf(' ') != -1) {
        throw new MalformedCookieException("Cookie name may not contain blanks");
    }
    if (cookie.getName().startsWith("$")) {
        throw new MalformedCookieException("Cookie name may not start with $");
    }

    if (cookie.getDomain() != null && (!cookie.getDomain().equals(host))) {

        // domain must start with dot
        if (!cookie.getDomain().startsWith(".")) {
            throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain()
                    + "\" violates RFC 2109: domain must start with a dot");
        }
        // domain must have at least one embedded dot
        int dotIndex = cookie.getDomain().indexOf('.', 1);
        if (dotIndex < 0 || dotIndex == cookie.getDomain().length() - 1) {
            throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain()
                    + "\" violates RFC 2109: domain must contain an embedded dot");
        }
        host = host.toLowerCase();
        if (!host.endsWith(cookie.getDomain())) {
            throw new MalformedCookieException("Illegal domain attribute \"" + cookie.getDomain()
                    + "\". Domain of origin: \"" + host + "\"");
        }
        // host minus domain may not contain any dots
        String hostWithoutDomain = host.substring(0, host.length() - cookie.getDomain().length());
        if (hostWithoutDomain.indexOf('.') != -1) {
            throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain()
                    + "\" violates RFC 2109: host minus domain may not contain any dots");
        }
    }
}

From source file:net.sourceforge.jwbf.core.actions.HttpActionClient.java

private HttpHost newHost(final URL url) {
    return new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
}

From source file:de.innovationgate.wgpublisher.WGPRequestPath.java

public static URL determineRedirectionURL(URL currentURL, String redirectProtocol, String redirectHost,
        String redirectPort) throws MalformedURLException {
    // determine current protocol, host and port
    String currentProtocol = currentURL.getProtocol();
    String currentHost = currentURL.getHost();
    String currentPort = null;// w w w .j  a  va  2  s.c  om
    if (currentURL.getPort() != -1) {
        currentPort = new Integer(currentURL.getPort()).toString();
    } else if ("http".equals(currentProtocol)) {
        currentPort = "80";
    } else if ("https".equals(currentProtocol)) {
        currentPort = "443";
    }

    //build redirectURL
    boolean redirectNecessary = false;
    StringBuffer redirectURLBuffer = new StringBuffer();
    if (redirectProtocol != null) {
        if (!currentProtocol.equalsIgnoreCase(redirectProtocol)) {
            redirectURLBuffer.append(redirectProtocol);
            redirectNecessary = true;
        } else {
            redirectURLBuffer.append(currentProtocol);
        }
    } else {
        redirectURLBuffer.append(currentProtocol);
    }

    redirectURLBuffer.append("://");

    if (redirectHost != null) {
        if (!currentHost.equalsIgnoreCase(redirectHost)) {
            redirectURLBuffer.append(redirectHost);
            redirectNecessary = true;
        } else {
            redirectURLBuffer.append(currentHost);
        }
    } else {
        redirectURLBuffer.append(currentHost);
    }

    if (redirectPort != null && currentPort != null) {
        if (!currentPort.equalsIgnoreCase(redirectPort)) {
            redirectURLBuffer.append(":" + redirectPort);
            redirectNecessary = true;
        } else {
            redirectURLBuffer.append(":" + currentPort);
        }
    } else if (currentPort != null) {
        redirectURLBuffer.append(":" + currentPort);
    }

    redirectURLBuffer.append(currentURL.getPath());

    if (currentURL.getQuery() != null) {
        redirectURLBuffer.append("?").append(currentURL.getQuery());
    }

    if (redirectNecessary) {
        URL redirectURL = new URL(redirectURLBuffer.toString());
        return redirectURL;
    } else {
        return null;
    }
}