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:IntergrationTest.OCSPIntegrationTest.java

private byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception {
    InputStream is = null;/* www. ja v a  2s .  c  om*/
    InputStream is_temp = null;
    try {
        if (uri == null)
            return null;
        URL url = uri.toURL();
        if (bActiveCheckUnknownHost) {
            url.getProtocol();
            String host = url.getHost();
            int port = url.getPort();
            if (port == -1)
                port = url.getDefaultPort();
            InetSocketAddress isa = new InetSocketAddress(host, port);
            if (isa.isUnresolved()) {
                //fix JNLP popup error issue
                throw new UnknownHostException("Host Unknown:" + isa.toString());
            }

        }
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setDoInput(true);
        uc.setAllowUserInteraction(false);
        uc.setInstanceFollowRedirects(true);
        setTimeout(uc);
        String contentEncoding = uc.getContentEncoding();
        int len = uc.getContentLength();
        // is = uc.getInputStream();
        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1) {
            is_temp = uc.getInputStream();
            is = new GZIPInputStream(is_temp);

        } else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1) {
            is_temp = uc.getInputStream();
            is = new InflaterInputStream(is_temp);

        } else {
            is = uc.getInputStream();

        }
        if (len != -1) {
            int ch, i = 0;
            byte[] res = new byte[len];
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);

            }
            return res;

        } else {
            ArrayList<byte[]> buffer = new ArrayList<>();
            int buf_len = 1024;
            byte[] res = new byte[buf_len];
            int ch, i = 0;
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);
                if (i == buf_len) {
                    //rotate
                    buffer.add(res);
                    i = 0;
                    res = new byte[buf_len];

                }

            }
            int total_len = buffer.size() * buf_len + i;
            byte[] buf = new byte[total_len];
            for (int j = 0; j < buffer.size(); j++) {
                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }
            if (i > 0) {
                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }
            return buf;

        }

    } catch (Exception e) {
        e.printStackTrace();
        return null;

    } finally {
        closeInputStream(is_temp);
        closeInputStream(is);

    }

}

From source file:io.hops.hopsworks.dela.DelaSetupWorker.java

private String getDelaTransferHttpEndpoint() throws HeartbeatException {
    String delaHttpEndpoint = settings.getDELA_TRANSFER_HTTP_ENDPOINT();
    try {//from  ww  w .jav  a 2 s . c o  m
        URL u = new URL(delaHttpEndpoint);
        u.toURI();
        // validate url syntax
        if (u.getHost().isEmpty() || u.getPort() == -1) {
            LOGGER.log(Level.WARNING, "{0} - malformed dela url. {1} - reset in database",
                    new Object[] { DelaException.Source.HOPS_SITE, delaHttpEndpoint });
            throw new HeartbeatException("DELA_TRANSFER_HTTP");
        }
        return delaHttpEndpoint;
    } catch (MalformedURLException | URISyntaxException ex) {
        LOGGER.log(Level.SEVERE, "{1} - malformed dela url. {1} - reset in database",
                new Object[] { DelaException.Source.HOPS_SITE, delaHttpEndpoint });
        throw new HeartbeatException("DELA_TRANSFER_HTTP");
    }
}

From source file:org.openqa.selenium.remote.internal.ApacheHttpAsyncClient.java

/**
 * Constructor.//ww w  .j  av  a 2s  . com
 *
 * @param client client.
 * @param url url.
 */
public ApacheHttpAsyncClient(CloseableHttpAsyncClient client, URL url) {
    this.client = checkNotNull(client, "null HttpClient");
    this.url = checkNotNull(url, "null URL");

    // Some machines claim "localhost.localdomain" is the same as "localhost".
    // This assumption is not always true.
    String host = url.getHost().replace(".localdomain", "");
    this.targetHost = new HttpHost(host, url.getPort(), url.getProtocol());
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.Location.java

/**
 * Returns the host portion of the location URL (the '[hostname]:[port]' portion).
 * @return the host portion of the location URL
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms533784.aspx">MSDN Documentation</a>
 *///from  w  w  w.  ja v  a2s.co  m
@JsxGetter
public String getHost() {
    final URL url = getUrl();
    final int port = url.getPort();
    final String host = url.getHost();

    if (port == -1) {
        return host;
    }
    return host + ":" + port;
}

From source file:sh.calaba.driver.server.DriverRegistrationHandler.java

/**
 * Performs actually the registration of the calabash driver node into the grid hub.
 * // w w  w. j a va 2 s.c o  m
 * @throws Exception On registration errors.
 */
public void performRegsitration() throws Exception {
    String tmp = "http://" + config.getHubHost() + ":" + config.getHubPort() + "/grid/register";

    HttpClient client = HttpClientFactory.getClient();

    URL registration = new URL(tmp);
    if (logger.isDebugEnabled()) {
        logger.debug("Registering the node to hub :" + registration);
    }
    BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
            registration.toExternalForm());
    JSONObject nodeConfig = getNodeConfig();
    r.setEntity(new StringEntity(nodeConfig.toString()));

    HttpHost host = new HttpHost(registration.getHost(), registration.getPort());
    HttpResponse response = client.execute(host, r);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new CalabashException("Error sending the registration request.");
    }
}

From source file:com.mindquarry.search.serializer.IndexPostSerializer.java

@Override
public void endDocument() throws SAXException {
    super.endDocument();

    Node node = this.res.getNode();
    Element root = (Element) ((Document) node).getFirstChild();
    String action = root.getAttribute("action"); //$NON-NLS-1$

    NodeList children = root.getChildNodes();

    if (true) { // should resolve the action and find out wether it is a
        // cycle through all children of the root element
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            // for every child element...
            if (child instanceof Element) {

                // block source which can be posted by creating a new
                // servlet request
                URL url = null;
                try {
                    url = new URL(action);
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                }//from w ww.  j  av  a 2s .  c  o m
                HttpClient client = new HttpClient();
                client.getState().setCredentials(
                        new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
                        new UsernamePasswordCredentials(login, password));

                PostMethod pMethod = new PostMethod(action);
                pMethod.setDoAuthentication(true);
                pMethod.addRequestHeader("accept", "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                TransformerFactory tf = TransformerFactory.newInstance();
                try {
                    tf.newTransformer().transform(new DOMSource(child), new StreamResult(baos));
                    pMethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
                    client.executeMethod(pMethod);
                } catch (TransformerConfigurationException e) {
                    getLogger().error("Failed to configure transformer prior to posting", e);
                } catch (TransformerException e) {
                    getLogger().error("Failed to transform prior to posting", e);
                } catch (HttpException e) {
                    getLogger().error("Failed to post", e);
                } catch (IOException e) {
                    getLogger().error("Something went wrong", e);
                }
            }
        }
    }
}

From source file:org.wso2.carbon.device.mgt.etc.apimgt.ApisAppClient.java

public void setBase64EncodedConsumerKeyAndSecret(List<DeviceTypeConfig> iotDeviceTypeConfigList) {
    if (!isEnabled) {
        return;//from   www  .  j a  v a 2s  .c  om
    }
    URL loginURL;
    try {
        loginURL = new URL(loginEndpoint);
    } catch (MalformedURLException e) {
        String errMsg = "Malformed URL " + loginEndpoint;
        log.error(errMsg);
        return;
    }
    HttpClient httpClient;
    try {
        httpClient = IoTUtil.getHttpClient(loginURL.getPort(), loginURL.getProtocol());
    } catch (Exception e) {
        log.error("Error on getting a http client for port :" + loginURL.getPort() + " protocol :"
                + loginURL.getProtocol());
        return;
    }

    HttpPost postMethod = new HttpPost(loginEndpoint);
    JSONObject apiJsonResponse;
    try {
        HttpResponse httpResponse = httpClient.execute(postMethod);
        String response = IoTUtil.getResponseString(httpResponse);
        if (log.isDebugEnabled()) {
            log.debug(response);
        }
        JSONObject jsonObject = new JSONObject(response);

        boolean apiError = jsonObject.getBoolean("error");
        if (!apiError) {
            String cookie = httpResponse.getHeaders("Set-Cookie")[0].getValue().split(";")[0];
            HttpGet getMethod = new HttpGet(subscriptionListEndpoint);
            getMethod.setHeader("cookie", cookie);
            httpResponse = httpClient.execute(getMethod);
            response = IoTUtil.getResponseString(httpResponse);

            if (log.isDebugEnabled()) {
                log.debug(response);
            }
            apiJsonResponse = new JSONObject(response);
            apiError = apiJsonResponse.getBoolean("error");
            if (apiError) {
                log.error("invalid subscription endpoint " + subscriptionListEndpoint);
                return;
            }
        } else {
            log.error("invalid access for login endpoint " + loginEndpoint);
            return;
        }
    } catch (IOException | JSONException | DeviceMgtCommonsException e) {
        log.warn("Trying to connect to the Api manager");
        return;
    }

    try {
        JSONArray jsonSubscriptions = apiJsonResponse.getJSONObject("subscriptions")
                .getJSONArray("applications");

        HashMap<String, String> subscriptionMap = new HashMap<>();
        for (int n = 0; n < jsonSubscriptions.length(); n++) {

            JSONObject object = jsonSubscriptions.getJSONObject(n);
            String appName = object.getString("name");
            String prodConsumerKey = object.getString("prodConsumerKey");
            String prodConsumerSecret = object.getString("prodConsumerSecret");
            subscriptionMap.put(appName,
                    new String(Base64.encodeBase64((prodConsumerKey + ":" + prodConsumerSecret).getBytes())));
        }

        for (DeviceTypeConfig iotDeviceTypeConfig : iotDeviceTypeConfigList) {
            String deviceType = iotDeviceTypeConfig.getType();
            String deviceTypeApiApplicationName = iotDeviceTypeConfig.getApiApplicationName();
            String base64EncodedString = subscriptionMap.get(deviceTypeApiApplicationName);
            if (base64EncodedString != null && base64EncodedString.length() != 0) {
                deviceTypeToApiAppMap.put(deviceType, base64EncodedString);
            }
        }
    } catch (JSONException e) {
        log.error("Json exception: " + e.getMessage(), e);
    }
}

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

/**
 * {@inheritDoc}// ww  w .  j a  va  2 s.co  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();
    }

    try {

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

        // serialize MediaPackage to target format
        OutputStream serOut = new ByteArrayOutputStream();
        MediaPackageParser.getAsXml(mp, serOut, false);
        String mpStr = serOut.toString();
        serOut.close();
        if (config.getFormat() == Configuration.Format.JSON) {
            JSONObject json = XML.toJSONObject(mpStr);
            mpStr = json.toString();
            if (mpStr.startsWith("{\"ns2:")) {
                mpStr = (new StringBuilder()).append("{\"").append(mpStr.substring(6)).toString();
            }
        }

        // 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) {
            if (config.debug()) {
                logger.info("Successfully submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString()
                        + ") to " + config.getUrl().toString() + ": 200 OK");
            }
        } 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 {
            throw new WorkflowOperationException(e);
        }
    }
    return createResult(mp, Action.CONTINUE);
}

From source file:jeeves.utils.XmlRequest.java

public XmlRequest(URL url) {
    this(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort(), url.getProtocol());

    address = url.getPath();/*w w  w.jav  a2 s .c o  m*/
    query = url.getQuery();
}