Search in sources :

Example 36 with HttpException

use of org.apache.commons.httpclient.HttpException in project openhab1-addons by openhab.

the class Connection method sendCommand.

/**
     * Send a command to the Particle REST API (convenience function).
     *
     * @param device
     *            the device context, or <code>null</code> if not needed for this command.
     * @param funcName
     *            the function name to call, or variable/field to retrieve if <code>command</code> is
     *            <code>null</code>.
     * @param user
     *            the user name to use in Basic Authentication if the funcName would require Basic Authentication.
     * @param pass
     *            the password to use in Basic Authentication if the funcName would require Basic Authentication.
     * @param command
     *            the command to send to the API.
     * @param proc
     *            a callback object that receives the status code and response body, or <code>null</code> if not
     *            needed.
     */
public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) {
    String url = null;
    String httpMethod = null;
    String content = null;
    String contentType = null;
    Properties headers = new Properties();
    logger.trace("sendCommand: funcName={}", funcName);
    switch(funcName) {
        case "createToken":
            httpMethod = HTTP_POST;
            url = TOKEN_URL;
            content = command;
            contentType = APPLICATION_FORM_URLENCODED;
            break;
        case "deleteToken":
            httpMethod = HTTP_DELETE;
            url = String.format(ACCESS_TOKENS_URL, tokens.accessToken);
            break;
        case "getDevices":
            httpMethod = HTTP_GET;
            url = String.format(GET_DEVICES_URL, tokens.accessToken);
            break;
        default:
            url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken);
            if (command == null) {
                // retrieve a variable
                httpMethod = HTTP_GET;
            } else {
                // call a function
                httpMethod = HTTP_POST;
                content = command;
                contentType = APPLICATION_JSON;
            }
            break;
    }
    HttpClient client = new HttpClient();
    if (!url.contains("access_token=")) {
        Credentials credentials = new UsernamePasswordCredentials(user, pass);
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }
    HttpMethod method = createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    for (String httpHeaderKey : headers.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey)));
        logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey));
    }
    try {
        // add content if a valid method is given ...
        if (method instanceof EntityEnclosingMethod && content != null) {
            EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
            eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null));
            logger.trace("content='{}', contentType='{}'", content, contentType);
        }
        if (logger.isDebugEnabled()) {
            try {
                logger.debug("About to execute '{}'", method.getURI());
            } catch (URIException e) {
                logger.debug(e.getMessage());
            }
        }
        int statusCode = client.executeMethod(method);
        if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
            logger.debug("Method failed: " + method.getStatusLine());
        }
        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug("Body of response: {}", responseBody);
        }
        if (proc != null) {
            proc.handleResponse(statusCode, responseBody);
        }
    } catch (HttpException he) {
        logger.warn("{}", he);
    } catch (IOException ioe) {
        logger.debug("{}", ioe);
    } finally {
        method.releaseConnection();
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) Properties(java.util.Properties) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 37 with HttpException

use of org.apache.commons.httpclient.HttpException in project openhab1-addons by openhab.

the class KM200Comm method getDataFromService.

/**
     * This function does the GET http communication to the device
     *
     */
public byte[] getDataFromService(String service) {
    byte[] responseBodyB64 = null;
    int maxNbrGets = 3;
    int statusCode = 0;
    // Create an instance of HttpClient.
    if (client == null) {
        client = new HttpClient();
    }
    synchronized (client) {
        // Create a method instance.
        GetMethod method = new GetMethod("http://" + device.getIP4Address() + service);
        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        // Set the right header
        method.setRequestHeader("Accept", "application/json");
        method.addRequestHeader("User-Agent", "TeleHeater/2.2.3");
        try {
            for (int i = 0; i < maxNbrGets && statusCode != HttpStatus.SC_OK; i++) {
                // Execute the method.
                statusCode = client.executeMethod(method);
                // Check the status
                switch(statusCode) {
                    case HttpStatus.SC_OK:
                        break;
                    case HttpStatus.SC_INTERNAL_SERVER_ERROR:
                        /* Unknown problem with the device, wait and try again */
                        logger.warn("HTTP GET failed: 500, internal server error, repeating.. ");
                        Thread.sleep(2000L);
                        continue;
                    case HttpStatus.SC_FORBIDDEN:
                        /* Service is available but not readable */
                        byte[] test = new byte[1];
                        return test;
                    default:
                        logger.error("HTTP GET failed: {}", method.getStatusLine());
                        return null;
                }
            }
            device.setCharSet(method.getResponseCharSet());
            // Read the response body.
            responseBodyB64 = ByteStreams.toByteArray(method.getResponseBodyAsStream());
        } catch (HttpException e) {
            logger.error("Fatal protocol violation: {}", e.getMessage());
        } catch (InterruptedException e) {
            logger.error("Sleep was interrupted: {}", e.getMessage());
        } catch (IOException e) {
            logger.error("Fatal transport error: {}", e.getMessage());
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        return responseBodyB64;
    }
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 38 with HttpException

use of org.apache.commons.httpclient.HttpException in project zaproxy by zaproxy.

the class ProxyThread method run.

@Override
public void run() {
    proxyThreadList.add(thread);
    boolean isSecure = this instanceof ProxyThreadSSL;
    HttpRequestHeader firstHeader = null;
    try {
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inSocket.getInputStream(), 2048);
        inSocket = new CustomStreamsSocket(inSocket, bufferedInputStream, inSocket.getOutputStream());
        httpIn = new HttpInputStream(inSocket);
        httpOut = new HttpOutputStream(inSocket.getOutputStream());
        firstHeader = httpIn.readRequestHeader(isSecure);
        firstHeader.setSenderAddress(inSocket.getInetAddress());
        if (firstHeader.getMethod().equalsIgnoreCase(HttpRequestHeader.CONNECT)) {
            HttpMessage connectMsg = new HttpMessage(firstHeader);
            connectMsg.setTimeSentMillis(System.currentTimeMillis());
            try {
                httpOut.write(CONNECT_HTTP_200);
                httpOut.flush();
                connectMsg.setResponseHeader(CONNECT_HTTP_200);
                connectMsg.setTimeElapsedMillis((int) (System.currentTimeMillis() - connectMsg.getTimeSentMillis()));
                notifyConnectMessage(connectMsg);
                byte[] bytes = new byte[3];
                bufferedInputStream.mark(3);
                bufferedInputStream.read(bytes);
                bufferedInputStream.reset();
                if (isSslTlsHandshake(bytes)) {
                    isSecure = true;
                    beginSSL(firstHeader.getHostName());
                }
                firstHeader = httpIn.readRequestHeader(isSecure);
                firstHeader.setSenderAddress(inSocket.getInetAddress());
                processHttp(firstHeader, isSecure);
            } catch (MissingRootCertificateException e) {
                // Unluckily Firefox and Internet Explorer will not show this message.
                // We should find a way to let the browsers display this error message.
                // May we can redirect to some kind of ZAP custom error page.
                final HttpMessage errmsg = new HttpMessage(firstHeader);
                setErrorResponse(errmsg, BAD_GATEWAY_RESPONSE_STATUS, e, "ZAP SSL Error");
                writeHttpResponse(errmsg, httpOut);
                throw new IOException(e);
            }
        } else {
            processHttp(firstHeader, isSecure);
        }
    } catch (SocketTimeoutException e) {
        // ZAP: Log the exception
        if (firstHeader != null) {
            if (HttpRequestHeader.CONNECT.equalsIgnoreCase(firstHeader.getMethod())) {
                log.warn("Timeout reading (client) message after CONNECT to " + firstHeader.getURI());
            } else {
                log.warn("Timeout accessing " + firstHeader.getURI());
            }
        } else {
            log.warn("Socket timeout while reading first message.");
            if (log.isDebugEnabled()) {
                log.debug(e, e);
            }
        }
    } catch (HttpMalformedHeaderException e) {
        log.warn("Malformed Header: ", e);
    } catch (HttpException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.debug("IOException: ", e);
    } finally {
        proxyThreadList.remove(thread);
        // ZAP: do only close if flag is false
        if (!keepSocketOpen) {
            disconnect();
        }
    }
}
Also used : HttpOutputStream(org.parosproxy.paros.network.HttpOutputStream) IOException(java.io.IOException) HttpRequestHeader(org.parosproxy.paros.network.HttpRequestHeader) MissingRootCertificateException(org.parosproxy.paros.security.MissingRootCertificateException) SocketTimeoutException(java.net.SocketTimeoutException) BufferedInputStream(java.io.BufferedInputStream) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) HttpException(org.apache.commons.httpclient.HttpException) HttpInputStream(org.parosproxy.paros.network.HttpInputStream) HttpMessage(org.parosproxy.paros.network.HttpMessage)

Example 39 with HttpException

use of org.apache.commons.httpclient.HttpException in project zaproxy by zaproxy.

the class SpiderTask method fetchResource.

/**
	 * Fetches a resource.
	 * 
	 * @return the response http message
	 * @throws HttpException the http exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws DatabaseException if an error occurred while reading the HTTP message
	 */
private HttpMessage fetchResource() throws IOException, DatabaseException {
    // Build fetch the request message from the database
    HttpMessage msg;
    try {
        msg = reference.getHttpMessage();
    } finally {
        deleteHistoryReference();
    }
    msg.getRequestHeader().setHeader(HttpHeader.IF_MODIFIED_SINCE, null);
    msg.getRequestHeader().setHeader(HttpHeader.IF_NONE_MATCH, null);
    // Check if there is a custom user agent
    if (parent.getSpiderParam().getUserAgent() != null) {
        msg.getRequestHeader().setHeader(HttpHeader.USER_AGENT, parent.getSpiderParam().getUserAgent());
    }
    //Check if there's a need to send the message from the point of view of a User
    if (parent.getScanUser() != null) {
        msg.setRequestingUser(parent.getScanUser());
    }
    // Fetch the page
    if (parent.getHttpSender() != null) {
        try {
            parent.getHttpSender().sendAndReceive(msg);
        } catch (ConnectException e) {
            log.debug("Failed to connect to: " + msg.getRequestHeader().getURI(), e);
            throw e;
        } catch (SocketTimeoutException e) {
            log.debug("Socket timeout: " + msg.getRequestHeader().getURI(), e);
            throw e;
        } catch (SocketException e) {
            log.debug("Socket exception: " + msg.getRequestHeader().getURI(), e);
            throw e;
        } catch (UnknownHostException e) {
            log.debug("Unknown host: " + msg.getRequestHeader().getURI(), e);
            throw e;
        } catch (Exception e) {
            log.error("An error occurred while fetching the resource [" + msg.getRequestHeader().getURI() + "]: " + e.getMessage(), e);
            throw e;
        }
    }
    return msg;
}
Also used : SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) HttpMessage(org.parosproxy.paros.network.HttpMessage) IOException(java.io.IOException) DatabaseException(org.parosproxy.paros.db.DatabaseException) URIException(org.apache.commons.httpclient.URIException) UnknownHostException(java.net.UnknownHostException) HttpMalformedHeaderException(org.parosproxy.paros.network.HttpMalformedHeaderException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) HttpException(org.apache.commons.httpclient.HttpException) ConnectException(java.net.ConnectException) ConnectException(java.net.ConnectException)

Example 40 with HttpException

use of org.apache.commons.httpclient.HttpException in project zm-mailbox by Zimbra.

the class TestPreAuthServlet method doPreAuthServletRequest.

void doPreAuthServletRequest(String preAuthUrl, boolean admin) throws Exception {
    Server localServer = Provisioning.getInstance().getLocalServer();
    String protoHostPort;
    if (admin)
        protoHostPort = "https://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    else
        protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);
    String url = protoHostPort + preAuthUrl;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    try {
        int respCode = HttpClientUtil.executeMethod(client, method);
        int statusCode = method.getStatusCode();
        String statusLine = method.getStatusLine().toString();
        System.out.println("respCode=" + respCode);
        System.out.println("statusCode=" + statusCode);
        System.out.println("statusLine=" + statusLine);
    /*
            System.out.println("Headers");
            Header[] respHeaders = method.getResponseHeaders();
            for (int i=0; i < respHeaders.length; i++) {
                String header = respHeaders[i].toString();
                System.out.println(header);
            }
            
            String respBody = method.getResponseBodyAsString();
            // System.out.println("respBody=" + respBody);
            */
    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        method.releaseConnection();
    }
}
Also used : Server(com.zimbra.cs.account.Server) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Aggregations

HttpException (org.apache.commons.httpclient.HttpException)62 IOException (java.io.IOException)55 HttpClient (org.apache.commons.httpclient.HttpClient)35 GetMethod (org.apache.commons.httpclient.methods.GetMethod)32 HttpMethod (org.apache.commons.httpclient.HttpMethod)22 InputStream (java.io.InputStream)16 Header (org.apache.commons.httpclient.Header)12 PostMethod (org.apache.commons.httpclient.methods.PostMethod)12 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)10 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)8 DeleteMethod (org.apache.commons.httpclient.methods.DeleteMethod)6 Test (org.junit.Test)5 ServiceException (com.zimbra.common.service.ServiceException)4 Server (com.zimbra.cs.account.Server)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 Date (java.util.Date)4 HashMap (java.util.HashMap)4 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)4 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)4 XStream (com.thoughtworks.xstream.XStream)3