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.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient.java

public JSONArray getAllCurrentUserSessions() throws DeviceControllerException {
    if (xmppEnabled) {
        JSONArray xmppSessions;/*from w  w  w.  ja  v  a  2 s. co  m*/
        String xmppSessionsAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + XMPP_SESSIONS_API;

        if (log.isDebugEnabled()) {
            log.debug("The Get-Sessions Endpoint URL of the XMPP Server is set to: " + xmppSessionsAPIEndpoint);
        }

        String encodedString = xmppUsername + ":" + xmppPassword;
        encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8)));
        String authorizationHeader = "Basic " + encodedString;

        URL xmppUserApiUrl;
        try {
            xmppUserApiUrl = new URL(xmppSessionsAPIEndpoint);
        } catch (MalformedURLException e) {
            String errMsg = "Malformed XMPP URL + " + xmppSessionsAPIEndpoint;
            log.error(errMsg);
            throw new DeviceControllerException(errMsg, e);
        }

        HttpClient httpClient;
        try {
            httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol());
        } catch (Exception e) {
            String errorMsg = "Error on getting a http client for port :" + xmppUserApiUrl.getPort()
                    + " protocol :" + xmppUserApiUrl.getProtocol();
            log.error(errorMsg);
            throw new DeviceControllerException(errorMsg, e);
        }

        HttpGet httpGet = new HttpGet(xmppSessionsAPIEndpoint);
        httpGet.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);
        httpGet.addHeader(HttpHeaders.ACCEPT, APPLICATION_JSON);

        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);

            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String errorMsg = "XMPP Server returned status: '"
                        + httpResponse.getStatusLine().getStatusCode()
                        + "' for checking current XMPP Sessions.";
                log.error(errorMsg);
                throw new DeviceControllerException(errorMsg);
            }

            String response = IoTUtil.getResponseString(httpResponse);
            xmppSessions = new JSONObject(response).getJSONArray("session");
            return xmppSessions;

        } catch (IOException e) {
            String errorMsg = "Error occured whilst trying a 'GET' at : " + xmppSessionsAPIEndpoint;
            log.error(errorMsg);
            throw new DeviceControllerException(errorMsg, e);
        }

    } else {
        String warnMsg = String.format("XMPP <Enabled> set to false in [%s]", DEVICEMGT_CONFIG_FILE);
        log.warn(warnMsg);
        throw new DeviceControllerException(warnMsg);
    }
}

From source file:org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient.java

public boolean createXMPPAccount(XmppAccount newUserAccount) throws DeviceControllerException {
    if (xmppEnabled) {
        String xmppUsersAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + XMPP_USERS_API;
        if (log.isDebugEnabled()) {
            log.debug("The Create-UserAccount Endpoint URL of the XMPP Server is set to: "
                    + xmppUsersAPIEndpoint);
        }//from   w w  w .  j a v a2 s .  c o  m

        String encodedString = xmppUsername + ":" + xmppPassword;
        encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8)));
        String authorizationHeader = "Basic " + encodedString;
        String jsonRequest = "{\n" + "    \"username\": \"" + newUserAccount.getUsername() + "\","
                + "    \"password\": \"" + newUserAccount.getPassword() + "\"," + "    \"name\": \""
                + newUserAccount.getAccountName() + "\"," + "    \"email\": \"" + newUserAccount.getEmail()
                + "\"," + "    \"properties\": {" + "        \"property\": [" + "            {"
                + "                \"@key\": \"console.rows_per_page\","
                + "                \"@value\": \"user-summary=8\"" + "            }," + "            {"
                + "                \"@key\": \"console.order\","
                + "                \"@value\": \"session-summary=1\"" + "            }" + "        ]" + "    }"
                + "}";

        StringEntity requestEntity;
        try {
            requestEntity = new StringEntity(jsonRequest, APPLICATION_JSON, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException e) {
            return false;
        }

        URL xmppUserApiUrl;
        try {
            xmppUserApiUrl = new URL(xmppUsersAPIEndpoint);
        } catch (MalformedURLException e) {
            String errMsg = "Malformed XMPP URL + " + xmppUsersAPIEndpoint;
            log.error(errMsg);
            throw new DeviceControllerException(errMsg);
        }
        HttpClient httpClient;
        try {
            httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol());
        } catch (Exception e) {
            log.error("Error on getting a http client for port :" + xmppUserApiUrl.getPort() + " protocol :"
                    + xmppUserApiUrl.getProtocol());
            return false;
        }

        HttpPost httpPost = new HttpPost(xmppUsersAPIEndpoint);
        httpPost.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);
        httpPost.setEntity(requestEntity);

        try {
            HttpResponse httpResponse = httpClient.execute(httpPost);

            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
                String response = IoTUtil.getResponseString(httpResponse);
                String errorMsg = "XMPP Server returned status: '"
                        + httpResponse.getStatusLine().getStatusCode() + "' for account creation with error:\n"
                        + response;
                log.error(errorMsg);
                throw new DeviceControllerException(errorMsg);
            } else {
                EntityUtils.consume(httpResponse.getEntity());
                return true;
            }
        } catch (IOException e) {
            String errorMsg = "Error occured whilst trying a 'POST' at : " + xmppUsersAPIEndpoint;
            log.error(errorMsg);
            throw new DeviceControllerException(errorMsg, e);
        }

    } else {
        log.warn(String.format("XMPP <Enabled> set to false in [%s]", DEVICEMGT_CONFIG_FILE));
        return false;
    }
}

From source file:org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient.java

public boolean doesXMPPUserAccountExist(String username) throws DeviceControllerException {
    if (xmppEnabled) {
        String xmppCheckUserAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + XMPP_USERS_API + "/"
                + username;/*from   ww  w  .  ja v  a2  s .c om*/
        if (log.isDebugEnabled()) {
            log.debug("The Check-User-Account Endpoint URL of the XMPP Server is set to: "
                    + xmppCheckUserAPIEndpoint);
        }

        String encodedString = xmppUsername + ":" + xmppPassword;
        encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8)));
        String authorizationHeader = "Basic " + encodedString;

        URL xmppUserApiUrl;
        try {
            xmppUserApiUrl = new URL(xmppCheckUserAPIEndpoint);
        } catch (MalformedURLException e) {
            String errMsg = "Malformed XMPP URL + " + xmppCheckUserAPIEndpoint;
            log.error(errMsg);
            throw new DeviceControllerException(errMsg, e);
        }

        HttpClient httpClient;
        try {
            httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol());
        } catch (Exception e) {
            String errorMsg = "Error on getting a http client for port :" + xmppUserApiUrl.getPort()
                    + " protocol :" + xmppUserApiUrl.getProtocol();
            log.error(errorMsg);
            throw new DeviceControllerException(errorMsg, e);
        }

        HttpGet httpGet = new HttpGet(xmppCheckUserAPIEndpoint);
        httpGet.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);

        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);

            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String response = IoTUtil.getResponseString(httpResponse);
                if (log.isDebugEnabled()) {
                    log.debug("XMPP Server returned status: '" + httpResponse.getStatusLine().getStatusCode()
                            + "' for checking existence of account [" + username + "] with message:\n"
                            + response + "\nProbably, an account with this username does not exist.");
                }
                return false;
            }

        } catch (IOException e) {
            String errorMsg = "Error occured whilst trying a 'GET' at : " + xmppCheckUserAPIEndpoint;
            log.error(errorMsg);
            throw new DeviceControllerException(errorMsg, e);
        }

        if (log.isDebugEnabled()) {
            log.debug("XMPP Server already has an account for the username - [" + username + "].");
        }
        return true;
    } else {
        String warnMsg = String.format("XMPP <Enabled> set to false in [%s]", DEVICEMGT_CONFIG_FILE);
        log.warn(warnMsg);
        throw new DeviceControllerException(warnMsg);
    }
}

From source file:com.adito.replacementproxy.ProxiedRequestDispatcher.java

/**
 * Send the request to the target server.
 * /*from   w  w w .  j av  a  2  s  . c o  m*/
 * @return request successful
 * @throws Exception on any error
 */
public boolean sendProxiedRequest() throws Exception {

    byte[] content = null;
    OutputStream serverOut = null;
    HttpClient client;
    SessionClients clients = null;
    HttpSession session = requestProcessor.getSession();

    // Manage the sessions clients
    synchronized (session) {
        clients = (SessionClients) session.getAttribute(Constants.HTTP_CLIENTS);
        if (clients == null) {
            clients = new SessionClients();
            session.setAttribute(Constants.HTTP_CLIENTS, clients);
        }
    }

    RequestParameterMap requestParameters = requestProcessor.getRequestParameters();
    URL proxiedURL = requestParameters.getProxiedURIDetails().getProxiedURL();

    synchronized (clients) {
        String key = proxiedURL.getHost() + ":"
                + (proxiedURL.getPort() > 0 ? proxiedURL.getPort()
                        : proxiedURL.getProtocol().equals("https") ? 443 : 80)
                + ":" + proxiedURL.getProtocol().equals("https") + ":"
                + requestProcessor.getWebForward().getResourceId() + Thread.currentThread().getName();
        client = (HttpClient) clients.get(key);

        if (client == null) {
            client = new HttpClient(proxiedURL.getHost(),
                    (proxiedURL.getPort() > 0 ? proxiedURL.getPort()
                            : proxiedURL.getProtocol().equals("https") ? 443 : 80),
                    proxiedURL.getProtocol().equals("https"));

            if (!requestProcessor.getWebForward().getPreferredAuthenticationScheme()
                    .equals(HttpAuthenticatorFactory.NONE)
                    && !requestProcessor.getWebForward().getAuthenticationUsername().equals("")
                    && !requestProcessor.getWebForward().getAuthenticationPassword().equals("")) {
                PasswordCredentials pwd = new PasswordCredentials();
                pwd.setUsername(SessionInfoReplacer.replace(requestProcessor.getSessionInfo(),
                        requestProcessor.getWebForward().getAuthenticationUsername()));
                pwd.setPassword(SessionInfoReplacer.replace(requestProcessor.getSessionInfo(),
                        requestProcessor.getWebForward().getAuthenticationPassword()));
                client.setCredentials(pwd);
            }

            // Set the preferred scheme
            client.setPreferredAuthentication(
                    requestProcessor.getWebForward().getPreferredAuthenticationScheme());

            // Do not track cookies, browser will instead
            client.setIncludeCookies(false);

            // If we're using basic authentication then preempt the 401
            // response
            client.setPreemtiveAuthentication(requestProcessor.getWebForward()
                    .getPreferredAuthenticationScheme().equalsIgnoreCase("BASIC"));
            clients.put(key, client);
        }
    }

    if (log.isDebugEnabled())
        log.debug("Connecting to [" + proxiedURL + "] ");

    ProxiedHttpMethod method;

    if (!requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_NONE)
            && !requestProcessor.getWebForward().getFormType().equals("")
            && !requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_JAVASCRIPT)
            && !Boolean.TRUE.equals(launchSession.getAttribute(LAUNCH_ATTR_AUTH_POSTED))) {

        /**
         * This code will automatically submit form parameters.
         * 
         * LDP - Use the full URI with parameters as we need to ensure parameters are sent as they are received.
         */
        method = new ProxiedHttpMethod(requestProcessor.getWebForward().getFormType(),
                SessionInfoReplacer.replace(requestProcessor.getSessionInfo(),
                        requestProcessor.getUriEncoded()),
                requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_POST)
                        ? new MultiMap()
                        : requestParameters,
                requestProcessor.getSessionInfo(),
                requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_POST));

        if (requestProcessor.getWebForward().getEncoding() != null
                && !requestProcessor.getWebForward().getEncoding().equals(WebForwardTypes.DEFAULT_ENCODING))
            method.setCharsetEncoding(requestProcessor.getWebForward().getEncoding());

        StringTokenizer tokens = new StringTokenizer(requestProcessor.getWebForward().getFormParameters(),
                "\n");
        int idx;
        String param;
        while (tokens.hasMoreTokens()) {
            param = SessionInfoReplacer.replace(requestProcessor.getLaunchSession().getSession(),
                    tokens.nextToken().trim());
            idx = param.indexOf('=');
            if (idx > -1 && idx < param.length() - 1) {
                method.addParameter(param.substring(0, idx), param.substring(idx + 1));
            } else
                method.addParameter(param, "");
        }

        launchSession.setAttribute(LAUNCH_ATTR_AUTH_POSTED, Boolean.TRUE);
    } else {
        /**
          * LDP - Use the full URI with parameters as we need to ensure parameters are sent as they are received.
         */
        method = new ProxiedHttpMethod(requestProcessor.getMethod(),
                SessionInfoReplacer.replace(requestProcessor.getSessionInfo(),
                        requestProcessor.getUriEncoded()),
                requestParameters, requestProcessor.getSessionInfo(),
                requestProcessor.getRequest().getContentType() != null && requestProcessor.getRequest()
                        .getContentType().startsWith("application/x-www-form-urlencoded"));

        if (requestProcessor.getWebForward().getEncoding() != null
                && !requestProcessor.getWebForward().getEncoding().equals(WebForwardTypes.DEFAULT_ENCODING))
            method.setCharsetEncoding(requestProcessor.getWebForward().getEncoding());
    }

    int contentLength = 0;
    String contentType = null;

    for (Enumeration e = requestProcessor.getHeaderNames(); e.hasMoreElements();) {

        String hdr = (String) e.nextElement();

        if (ignoreHeaders.containsKey(hdr)) {
            if (log.isDebugEnabled())
                log.debug("Ignoring " + hdr + " = " + requestProcessor.getHeader(hdr));
            continue;
        }

        // See if there any replacements for this header
        List replacements = WebForwardDatabaseFactory.getInstance().getReplacementsForContent(
                launchSession.getSession().getUser().getPrincipalName(),
                Replacement.REPLACEMENT_TYPE_SENT_HEADER, hdr, proxiedURL.toExternalForm());

        Enumeration vals = requestProcessor.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();

            // Do the replacements
            for (Iterator i = replacements.iterator(); i.hasNext();) {
                Replacement r = (Replacement) i.next();
                val = val.replaceAll(r.getMatchPattern(), r.getReplacePattern());
            }

            if (val != null) {
                if (hdr.equalsIgnoreCase(HttpConstants.HDR_HOST)) {
                    if (proxiedURL.getPort() == -1) {
                        val = proxiedURL.getHost();
                    } else {
                        val = proxiedURL.getHost() + ":" + proxiedURL.getPort();
                    }
                } else if (hdr.equalsIgnoreCase(HttpConstants.HDR_COOKIE)) {
                    // We shouldnt supply our local cookies
                    if (log.isDebugEnabled())
                        log.debug(" Splitting cookie " + val);
                    String[] cookieVals = val.split("\\;");
                    StringBuffer newVal = new StringBuffer();
                    for (int i = 0; i < cookieVals.length; i++) {
                        if (log.isDebugEnabled())
                            log.debug("Cookie = " + cookieVals[i]);
                        int idx = cookieVals[i].indexOf('=');
                        String cn = "";
                        String cv = "";
                        if (idx == -1) {
                            cn = Util.trimBoth(cookieVals[i]);
                        } else if (idx < cookieVals[i].length() - 1) {
                            cn = Util.trimBoth(cookieVals[i].substring(0, idx));
                            cv = Util.trimBoth(cookieVals[i].substring(idx + 1));
                        } else {
                            cn = Util.trimBoth(cookieVals[i].substring(0, idx));
                        }
                        if (cn.equals("webForward") || cn.equals(Constants.LOGON_TICKET)
                                || cn.equals(Constants.DOMAIN_LOGON_TICKET) || (cn.equals(sessionIdCookieName)
                                        && cv.equals(requestProcessor.getSession().getId()))) {
                            if (log.isDebugEnabled())
                                log.debug("  Omiting cookie " + cn + "=" + cv);
                        } else {
                            // TODO is it ok to store the cookie map in
                            // memory?
                            CookieItem cookie = cookieMap.getByFakeCookieName(cn);
                            if (cookie == null) {
                                if (log.isDebugEnabled())
                                    log.debug("  Cookie " + cn + " unmapped, ignoring");
                                // Un-mapped cookie, ignore
                            } else {
                                if (log.isDebugEnabled())
                                    log.debug("  Including cookie " + cn + "=" + cv);
                                if (newVal.length() > 0) {
                                    newVal.append("; ");
                                }
                                newVal.append(cookie.getRealCookieName());
                                newVal.append("=");
                                newVal.append(Util.urlDecode(cv));
                            }
                        }
                    }
                    if (newVal.length() == 0) {
                        if (log.isDebugEnabled())
                            log.debug("Send no cookies");
                        val = null;
                    } else {
                        val = newVal.toString();
                        if (log.isDebugEnabled())
                            log.debug("Using cooking val of " + val);
                    }
                }
                // Change the refererer
                else if (hdr.equalsIgnoreCase(HttpConstants.HDR_REFERER)) {
                    try {
                        URL refUrl = new URL(val);
                        refUrl.getQuery();
                        if (log.isDebugEnabled())
                            log.debug("Splitting refererer query string [" + val + "] " + refUrl.getQuery());
                        if (refUrl.getFile() != null) {

                            ProxyURIDetails uriDetails = RequestParameterMap.parseProxyPath(refUrl.getFile(),
                                    "UTF-8");
                            if (uriDetails.getProxiedURL() == null) {
                                /* If the referer is not a proxied URL then don't send a referer. This
                                 * way a target server won't know its a request from Adito by
                                 * examining the referer
                                 */
                                val = null;
                            } else {
                                val = uriDetails.getProxiedURL().toExternalForm();
                            }
                        }
                    } catch (MalformedURLException murle) {

                    }
                } else if (hdr.equalsIgnoreCase(HttpConstants.HDR_CONTENT_LENGTH)) {
                    contentLength = Integer.parseInt(val);
                    continue;
                } else if (hdr.equalsIgnoreCase(HttpConstants.HDR_CONTENT_TYPE)) {
                    contentType = val;
                    continue;
                } else if (hdr.equalsIgnoreCase(HttpConstants.HDR_CONNECTION)) {
                    // Handled by the Maverick HTTP client
                    continue;
                }

                if (val != null) {
                    method.getProxiedRequest().addHeaderField(hdr, val);
                }

                if (log.isDebugEnabled())
                    log.debug("Adding request property " + hdr + " = " + val);
            }
        }
    }

    // Proxy headers
    method.getProxiedRequest().setHeaderField("Via", Branding.PRODUCT_NAME);

    if (requestParameters.isMultipart() && requestParameters.getMultipartDataLength() > 0) {
        method.setContent(getDebugStream(requestParameters.getMultipartData()),
                requestParameters.getMultipartDataLength(), requestParameters.getOriginalContentType());
    } else if (!requestParameters.isWwwFormURLEncoded() && contentLength > 0) {
        method.setContent(getDebugStream(requestProcessor.getRequest().getInputStream()),
                requestParameters.getOriginalContentLength(), requestParameters.getOriginalContentType());
    }

    serverResponse = client.execute(method);

    responseCode = serverResponse.getStatus();
    responseMessage = serverResponse.getReason();

    return true;
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLAnchorElement.java

/**
 * Returns the host portion of the link's URL (the '[hostname]:[port]' portion).
 * @return the host portion of the link's URL
 * @throws Exception if an error occurs/*w w  w  .  j av  a 2 s .  c  om*/
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms533784.aspx">MSDN Documentation</a>
 */
@JsxGetter
public String getHost() throws Exception {
    try {
        final URL url = getUrl();
        final int port = url.getPort();
        final String host = url.getHost();

        if (port == -1) {
            return host;
        }
        return host + ":" + port;
    } catch (final MalformedURLException e) {
        return "";
    }
}

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.ServiceInvoker.java

/**
 * //from www.j a v  a2s .  c om
 * 
 */
public static int invoke(URL url, String userName, String password, Map<String, String> headers,
        InputStream input, HttpServletResponse output, OutputStream errorOut, int connectionTimeout,
        int soTimeout) throws IOException, SocketTimeoutException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    manager.getParams().setConnectionTimeout(connectionTimeout);
    manager.getParams().setSoTimeout(soTimeout);
    manager.getParams().setMaxConnectionsPerHost(client.getHostConfiguration(), 2);
    client.setHttpConnectionManager(manager);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));

    PostMethod method = new PostMethod(url.getFile());
    method.setRequestEntity(new InputStreamRequestEntity(input));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        method.addRequestHeader(e.getKey(), e.getValue());
    }
    if (!headers.containsKey("Content-Type"))
        method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if (!headers.containsKey("Accept"))
        method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
    if (!headers.containsKey("SOAPAction"))
        method.addRequestHeader("SOAPAction", "\"\"");
    if (!headers.containsKey("User-Agent"))
        method.addRequestHeader("User-Agent", "Langrid Service Invoker/1.0");
    if (userName != null) {
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
            if (port == -1) {
                port = 80;
            }
        }
        if (password == null) {
            password = "";
        }
        client.getState().setCredentials(new AuthScope(url.getHost(), port, null),
                new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        method.setDoAuthentication(true);
    }

    try {
        int status;
        try {
            status = client.executeMethod(method);
        } catch (SocketTimeoutException e) {
            status = HttpServletResponse.SC_REQUEST_TIMEOUT;
        }
        output.setStatus(status);
        if (status == 200) {
            for (Header h : method.getResponseHeaders()) {
                String name = h.getName();
                if (name.startsWith("X-Langrid") || (!throughHeaders.contains(name.toLowerCase())))
                    continue;
                String value = h.getValue();
                output.addHeader(name, value);
            }
            OutputStream os = output.getOutputStream();
            StreamUtil.transfer(method.getResponseBodyAsStream(), os);
            os.flush();
        } else if (status == HttpServletResponse.SC_REQUEST_TIMEOUT) {
        } else {
            StreamUtil.transfer(method.getResponseBodyAsStream(), errorOut);
        }
        return status;
    } finally {
        manager.shutdown();
    }
}

From source file:org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient.java

public void deleteCurrentXmppSessions() throws DeviceControllerException {
    JSONArray xmppSessionsArray;/*from   ww w .  j  a va2  s . c  o  m*/
    try {
        xmppSessionsArray = getAllCurrentUserSessions();
    } catch (DeviceControllerException e) {
        if (e.getMessage().contains(DEVICEMGT_CONFIG_FILE)) {
            log.warn(String.format("XMPP <Enabled> set to false in [%s]", DEVICEMGT_CONFIG_FILE));
            return;
        } else {
            throw e;
        }
    }

    if (xmppSessionsArray.length() != 0) {
        String xmppSessionsAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + XMPP_SESSIONS_API;
        String encodedString = xmppUsername + ":" + xmppPassword;
        encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8)));
        String authorizationHeader = "Basic " + encodedString;

        if (log.isDebugEnabled()) {
            log.debug("The Get-Sessions Endpoint URL of the XMPP Server is set to: " + xmppSessionsAPIEndpoint);
        }

        URL xmppUserApiUrl;
        try {
            xmppUserApiUrl = new URL(xmppSessionsAPIEndpoint);
        } catch (MalformedURLException e) {
            String errMsg = "Malformed XMPP URL + " + xmppSessionsAPIEndpoint;
            log.error(errMsg);
            throw new DeviceControllerException(errMsg, e);
        }

        HttpClient httpClient;
        try {
            httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol());
        } catch (Exception e) {
            String errorMsg = "Error on getting a http client for port :" + xmppUserApiUrl.getPort()
                    + " protocol :" + xmppUserApiUrl.getProtocol();
            log.error(errorMsg);
            throw new DeviceControllerException(errorMsg, e);
        }

        for (int i = 0; i < xmppSessionsArray.length(); i++) {

            String sessionName = xmppSessionsArray.getJSONObject(i).getString("username");
            String xmppUserSessionsAPIEndpoint = xmppSessionsAPIEndpoint + "/" + sessionName;

            HttpDelete httpDelete = new HttpDelete(xmppUserSessionsAPIEndpoint);
            httpDelete.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);

            try {
                HttpResponse httpResponse = httpClient.execute(httpDelete);

                if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    String errorMsg = "XMPP Server returned status: '"
                            + httpResponse.getStatusLine().getStatusCode()
                            + "' for checking current XMPP Sessions.";
                    log.error(errorMsg);
                    throw new DeviceControllerException(errorMsg);
                }

            } catch (IOException e) {
                String errorMsg = "Error occured whilst trying a 'DELETE' user-session [" + sessionName + "] "
                        + "at : " + xmppUserSessionsAPIEndpoint;
                log.error(errorMsg);
                throw new DeviceControllerException(errorMsg, e);
            }
        }
    }
}

From source file:io.selendroid.standalone.server.grid.SelfRegisteringRemote.java

public void performRegistration() throws Exception {
    String tmp = config.getRegistrationUrl();

    HttpClient client = HttpClientUtil.getHttpClient();

    URL registration = new URL(tmp);
    if (log.isLoggable(Level.INFO)) {
        log.info("Registering selendroid node to Selenium Grid hub :" + registration);
    }//from w  w w .  j  ava2s .c o m
    BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
            registration.toExternalForm());
    JSONObject nodeConfig = getNodeConfig();
    String nodeConfigString = nodeConfig.toString();
    if (log.isLoggable(Level.INFO)) {
        log.info("Registering selendroid node with following config:\n" + nodeConfigString);
    }
    r.setEntity(new StringEntity(nodeConfigString));

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

From source file:com.google.acre.script.NHttpAsyncUrlfetch.java

private Scriptable callback_result(long start_time, URL url, HttpResponse res, boolean system,
        boolean log_to_user, String response_encoding) {
    BrowserCompatSpecFactory bcsf = new BrowserCompatSpecFactory();
    CookieSpec cspec = bcsf.newInstance(null);
    String protocol = url.getProtocol();
    boolean issecure = ("https".equals(protocol));
    int port = url.getPort();
    if (port == -1)
        port = 80;//from  ww  w .ja v  a  2s. c  om
    CookieOrigin origin = new CookieOrigin(url.getHost(), port, url.getPath(), issecure);

    Object body = "";
    int status = res.getStatusLine().getStatusCode();

    Context ctx = Context.getCurrentContext();
    Scriptable out = ctx.newObject(_scope);
    Scriptable headers = ctx.newObject(_scope);
    Scriptable cookies = ctx.newObject(_scope);

    out.put("status", out, status);
    out.put("headers", out, headers);
    out.put("cookies", out, cookies);

    Header content_type_header = null;

    StringBuilder response_header_log = new StringBuilder();
    for (Header h : res.getAllHeaders()) {
        if (h.getName().equalsIgnoreCase("set-cookie")) {
            String set_cookie = h.getValue();
            Matcher m = Pattern.compile("\\s*(([^,]|(,\\s*\\d))+)").matcher(set_cookie);
            while (m.find()) {
                Header ch = new BasicHeader("Set-Cookie", set_cookie.substring(m.start(), m.end()));
                try {
                    List<Cookie> pcookies = cspec.parse(ch, origin);
                    for (Cookie c : pcookies) {
                        cookies.put(c.getName(), cookies, new AcreCookie(c).toJsObject(_scope));
                    }
                } catch (MalformedCookieException e) {
                    throw new RuntimeException(e);
                }
            }
        } else if (h.getName().equalsIgnoreCase("content-type")) {
            content_type_header = h;
        }

        response_header_log.append(h.getName() + ": " + h.getValue() + "\r\n");
        headers.put(h.getName(), headers, h.getValue());
    }

    String charset = null;
    if (content_type_header != null) {
        HeaderElement values[] = content_type_header.getElements();
        if (values.length == 1) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }

    if (charset == null)
        charset = response_encoding;

    // read body
    HttpEntity ent = res.getEntity();
    try {
        if (ent != null) {
            InputStream res_stream = ent.getContent();
            Header cenc = ent.getContentEncoding();
            if (cenc != null && res_stream != null) {
                HeaderElement[] codecs = cenc.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        res_stream = new GZIPInputStream(res_stream);
                    }
                }
            }

            long first_byte_time = 0;
            long end_time = 0;
            if (content_type_header != null && (content_type_header.getValue().startsWith("image/")
                    || content_type_header.getValue().startsWith("application/octet-stream")
                    || content_type_header.getValue().startsWith("multipart/form-data"))) {
                // HttpClient's InputStream doesn't support mark/reset, so
                // wrap it with one that does.
                BufferedInputStream bufis = new BufferedInputStream(res_stream);
                bufis.mark(2);
                bufis.read();
                first_byte_time = System.currentTimeMillis();
                bufis.reset();
                byte[] data = IOUtils.toByteArray(bufis);

                end_time = System.currentTimeMillis();
                body = new JSBinary();
                ((JSBinary) body).set_data(data);

                try {
                    if (res_stream != null)
                        res_stream.close();
                } catch (IOException e) {
                    // ignore
                }
            } else if (res_stream == null || charset == null) {
                first_byte_time = end_time = System.currentTimeMillis();
                body = "";
            } else {
                StringWriter writer = new StringWriter();
                Reader reader = new InputStreamReader(res_stream, charset);
                int i = reader.read();
                first_byte_time = System.currentTimeMillis();
                writer.write(i);
                IOUtils.copy(reader, writer);
                end_time = System.currentTimeMillis();
                body = writer.toString();

                try {
                    reader.close();
                    writer.close();
                } catch (IOException e) {
                    // ignore
                }
            }

            long reading_time = end_time - first_byte_time;
            long waiting_time = first_byte_time - start_time;

            String httprephdr = response_header_log.toString();
            // XXX need to log start-time of request
            _logger.syslog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status",
                    Integer.toString(status), "Headers", httprephdr, "Reading time", reading_time,
                    "Waiting time", waiting_time);

            if (system && log_to_user) {
                _response.userlog4j("DEBUG", "urlfetch.response.async", "URL", url.toString(), "Status",
                        Integer.toString(status), "Headers", httprephdr);

            }

            // XXX seems like AcreResponse should be able to use
            // the statistics object to generate x-metaweb-cost
            // given a bit of extra information

            Statistics.instance().collectUrlfetchTime(start_time, first_byte_time, end_time);

            _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw",
                    waiting_time);

        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    out.put("body", out, body);

    return out;
}