Search in sources :

Example 1 with MethodNotSupportedException

use of org.apache.http.MethodNotSupportedException in project openhab1-addons by openhab.

the class StreamClientImpl method createHttpRequest.

protected HttpUriRequest createHttpRequest(UpnpMessage upnpMessage, UpnpRequest upnpRequestOperation) throws MethodNotSupportedException {
    switch(upnpRequestOperation.getMethod()) {
        case GET:
            return new HttpGet(upnpRequestOperation.getURI());
        case SUBSCRIBE:
            return new HttpGet(upnpRequestOperation.getURI()) {

                @Override
                public String getMethod() {
                    return UpnpRequest.Method.SUBSCRIBE.getHttpName();
                }
            };
        case UNSUBSCRIBE:
            return new HttpGet(upnpRequestOperation.getURI()) {

                @Override
                public String getMethod() {
                    return UpnpRequest.Method.UNSUBSCRIBE.getHttpName();
                }
            };
        case POST:
            HttpEntityEnclosingRequest post = new HttpPost(upnpRequestOperation.getURI());
            post.setEntity(createHttpRequestEntity(upnpMessage));
            // Fantastic API
            return (HttpUriRequest) post;
        case NOTIFY:
            HttpEntityEnclosingRequest notify = new HttpPost(upnpRequestOperation.getURI()) {

                @Override
                public String getMethod() {
                    return UpnpRequest.Method.NOTIFY.getHttpName();
                }
            };
            notify.setEntity(createHttpRequestEntity(upnpMessage));
            // Fantastic API
            return (HttpUriRequest) notify;
        default:
            throw new MethodNotSupportedException(upnpRequestOperation.getHttpMethodName());
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) HttpGet(org.apache.http.client.methods.HttpGet) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) MethodNotSupportedException(org.apache.http.MethodNotSupportedException)

Example 2 with MethodNotSupportedException

use of org.apache.http.MethodNotSupportedException in project robovm by robovm.

the class HttpService method handleException.

protected void handleException(final HttpException ex, final HttpResponse response) {
    if (ex instanceof MethodNotSupportedException) {
        response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
    } else if (ex instanceof UnsupportedHttpVersionException) {
        response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED);
    } else if (ex instanceof ProtocolException) {
        response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
    } else {
        response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }
    byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage());
    ByteArrayEntity entity = new ByteArrayEntity(msg);
    entity.setContentType("text/plain; charset=US-ASCII");
    response.setEntity(entity);
}
Also used : ProtocolException(org.apache.http.ProtocolException) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) MethodNotSupportedException(org.apache.http.MethodNotSupportedException) UnsupportedHttpVersionException(org.apache.http.UnsupportedHttpVersionException)

Example 3 with MethodNotSupportedException

use of org.apache.http.MethodNotSupportedException in project XobotOS by xamarin.

the class HttpService method handleException.

protected void handleException(final HttpException ex, final HttpResponse response) {
    if (ex instanceof MethodNotSupportedException) {
        response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
    } else if (ex instanceof UnsupportedHttpVersionException) {
        response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED);
    } else if (ex instanceof ProtocolException) {
        response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
    } else {
        response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }
    byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage());
    ByteArrayEntity entity = new ByteArrayEntity(msg);
    entity.setContentType("text/plain; charset=US-ASCII");
    response.setEntity(entity);
}
Also used : ProtocolException(org.apache.http.ProtocolException) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) MethodNotSupportedException(org.apache.http.MethodNotSupportedException) UnsupportedHttpVersionException(org.apache.http.UnsupportedHttpVersionException)

Example 4 with MethodNotSupportedException

use of org.apache.http.MethodNotSupportedException in project iaf by ibissource.

the class CmisHttpSender method getMethod.

@Override
public HttpRequestBase getMethod(URIBuilder uri, String message, ParameterValueList pvl, Map<String, String> headersParamsMap, IPipeLineSession session) throws SenderException {
    HttpRequestBase method = null;
    try {
        if (getMethodType().equals("GET")) {
            method = new HttpGet(uri.build());
        } else if (getMethodType().equals("POST")) {
            HttpPost httpPost = new HttpPost(uri.build());
            // send data
            if (pvl.getParameterValue("writer") != null) {
                Output writer = (Output) pvl.getParameterValue("writer").getValue();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION);
                if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                    httpPost.setHeader("Content-Encoding", "gzip");
                    writer.write(new GZIPOutputStream(out, 4096));
                } else {
                    writer.write(out);
                }
                HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                httpPost.setEntity(entity);
                out.close();
                method = httpPost;
            }
        } else if (getMethodType().equals("PUT")) {
            HttpPut httpPut = new HttpPut(uri.build());
            // send data
            if (pvl.getParameterValue("writer") != null) {
                Output writer = (Output) pvl.getParameterValue("writer").getValue();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION);
                if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                    httpPut.setHeader("Content-Encoding", "gzip");
                    writer.write(new GZIPOutputStream(out, 4096));
                } else {
                    writer.write(out);
                }
                HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                httpPut.setEntity(entity);
                out.close();
                method = httpPut;
            }
        } else if (getMethodType().equals("DELETE")) {
            method = new HttpDelete(uri.build());
        } else {
            throw new MethodNotSupportedException("method [" + getMethodType() + "] not implemented");
        }
    } catch (Exception e) {
        throw new SenderException(e);
    }
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        log.debug("append header [" + entry.getKey() + "] with value [" + entry.getValue() + "]");
        method.addHeader(entry.getKey(), entry.getValue());
    }
    // Cmis creates it's own contentType depending on the method and bindingType
    method.setHeader("Content-Type", getContentType());
    log.debug(getLogPrefix() + "HttpSender constructed " + getMethodType() + "-method [" + method.getURI() + "] query [" + method.getURI().getQuery() + "] ");
    return method;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpGet(org.apache.http.client.methods.HttpGet) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpPut(org.apache.http.client.methods.HttpPut) CmisConnectionException(org.apache.chemistry.opencmis.commons.exceptions.CmisConnectionException) MethodNotSupportedException(org.apache.http.MethodNotSupportedException) IOException(java.io.IOException) TimeOutException(nl.nn.adapterframework.core.TimeOutException) SenderException(nl.nn.adapterframework.core.SenderException) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) GZIPOutputStream(java.util.zip.GZIPOutputStream) Output(org.apache.chemistry.opencmis.client.bindings.spi.http.Output) MethodNotSupportedException(org.apache.http.MethodNotSupportedException) SenderException(nl.nn.adapterframework.core.SenderException) Map(java.util.Map)

Example 5 with MethodNotSupportedException

use of org.apache.http.MethodNotSupportedException in project iaf by ibissource.

the class HttpSenderBase method sendMessageWithTimeoutGuarded.

@Override
public String sendMessageWithTimeoutGuarded(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException {
    ParameterValueList pvl = null;
    try {
        if (prc != null && paramList != null) {
            pvl = prc.getValues(paramList);
        }
    } catch (ParameterException e) {
        throw new SenderException(getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e);
    }
    URIBuilder uri;
    HttpRequestBase httpRequestBase;
    try {
        if (urlParameter != null) {
            String url = (String) pvl.getParameterValue(getUrlParam()).getValue();
            uri = getURI(url);
        } else {
            uri = staticUri;
        }
        httpTarget = new HttpHost(uri.getHost(), getPort(uri), uri.getScheme());
        Map<String, String> headersParamsMap = new HashMap<String, String>();
        if (headersParams != null) {
            StringTokenizer st = new StringTokenizer(headersParams, ",");
            while (st.hasMoreElements()) {
                headersParamsMap.put(st.nextToken(), null);
            }
        }
        if (isEncodeMessages()) {
            message = URLEncoder.encode(message, getCharSet());
        }
        httpRequestBase = getMethod(uri, message, pvl, headersParamsMap, prc.getSession());
        if (httpRequestBase == null)
            throw new MethodNotSupportedException("could not find implementation for method [" + getMethodType() + "]");
        if (!"POST".equals(getMethodType()) && !"PUT".equals(getMethodType()) && !"REPORT".equals(getMethodType())) {
            httpClientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {

                @Override
                protected boolean isRedirectable(String method) {
                    return true;
                }
            });
        }
        if (StringUtils.isNotEmpty(getContentType())) {
            httpRequestBase.setHeader("Content-Type", getContentType());
        }
        if (credentials != null && !StringUtils.isEmpty(credentials.getUsername())) {
            AuthCache authCache = httpClientContext.getAuthCache();
            if (authCache == null)
                authCache = new BasicAuthCache();
            authCache.put(httpTarget, new BasicScheme());
            httpClientContext.setAuthCache(authCache);
        }
        log.info(getLogPrefix() + "configured httpclient for host [" + uri.getHost() + "]");
    } catch (Exception e) {
        throw new SenderException(e);
    }
    CloseableHttpClient httpClient = httpClientBuilder.build();
    String result = null;
    int statusCode = -1;
    int count = getMaxExecuteRetries();
    String msg = null;
    while (count-- >= 0 && statusCode == -1) {
        try {
            log.debug(getLogPrefix() + "executing method [" + httpRequestBase.getRequestLine() + "]");
            HttpResponse httpResponse = httpClient.execute(httpTarget, httpRequestBase, httpClientContext);
            log.debug(getLogPrefix() + "executed method");
            HttpResponseHandler responseHandler = new HttpResponseHandler(httpResponse);
            StatusLine statusline = httpResponse.getStatusLine();
            statusCode = statusline.getStatusCode();
            if (StringUtils.isNotEmpty(getResultStatusCodeSessionKey()) && prc != null) {
                prc.getSession().put(getResultStatusCodeSessionKey(), Integer.toString(statusCode));
            }
            if (statusCode != HttpServletResponse.SC_OK) {
                log.warn(getLogPrefix() + "status [" + statusline.toString() + "]");
            } else {
                log.debug(getLogPrefix() + "status [" + statusCode + "]");
            }
            result = extractResult(responseHandler, prc);
            log.debug(getLogPrefix() + "retrieved result [" + result + "]");
        } catch (ClientProtocolException e) {
            httpRequestBase.abort();
            Throwable throwable = e.getCause();
            String cause = null;
            if (throwable != null) {
                cause = throwable.toString();
            }
            msg = e.getMessage();
            log.warn(getLogPrefix() + "httpException with message [" + msg + "] and cause [" + cause + "], executeRetries left [" + count + "]");
        } catch (IOException e) {
            httpRequestBase.abort();
            if (e instanceof SocketTimeoutException) {
                throw new TimeOutException(e);
            }
            throw new SenderException(e);
        } finally {
        // By forcing the use of the HttpResponseHandler the resultStream
        // will automatically be closed when it has been read.
        // See HttpResponseHandler and ReleaseConnectionAfterReadInputStream.
        // We cannot close the connection as the response might be kept
        // in a sessionKey for later use in the pipeline.
        // 
        // IMPORTANT: It is possible that poorly written implementations
        // wont read or close the response.
        // This will cause the connection to become stale..
        }
    }
    if (statusCode == -1) {
        if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) {
            // java.net.SocketTimeoutException: Read timed out
            throw new TimeOutException("Failed to recover from timeout exception");
        }
        throw new SenderException("Failed to recover from exception");
    }
    if (isXhtml() && StringUtils.isNotEmpty(result)) {
        result = XmlUtils.skipDocTypeDeclaration(result.trim());
        if (result.startsWith("<html>") || result.startsWith("<html ")) {
            CleanerProperties props = new CleanerProperties();
            HtmlCleaner cleaner = new HtmlCleaner(props);
            TagNode tagNode = cleaner.clean(result);
            result = new SimpleXmlSerializer(props).getXmlAsString(tagNode);
            if (transformerPool != null) {
                log.debug(getLogPrefix() + " transforming result [" + result + "]");
                ParameterResolutionContext prc_xslt = new ParameterResolutionContext(result, null, true, true);
                try {
                    result = transformerPool.transform(prc_xslt.getInputSource(), null);
                } catch (Exception e) {
                    throw new SenderException("Exception on transforming input", e);
                }
            }
        }
    }
    return result;
}
Also used : ParameterValueList(nl.nn.adapterframework.parameters.ParameterValueList) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HashMap(java.util.HashMap) SimpleXmlSerializer(org.htmlcleaner.SimpleXmlSerializer) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpHost(org.apache.http.HttpHost) DefaultRedirectStrategy(org.apache.http.impl.client.DefaultRedirectStrategy) ParameterException(nl.nn.adapterframework.core.ParameterException) CleanerProperties(org.htmlcleaner.CleanerProperties) ParameterResolutionContext(nl.nn.adapterframework.parameters.ParameterResolutionContext) BasicScheme(org.apache.http.impl.auth.BasicScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) SenderException(nl.nn.adapterframework.core.SenderException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) SocketTimeoutException(java.net.SocketTimeoutException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) MethodNotSupportedException(org.apache.http.MethodNotSupportedException) IOException(java.io.IOException) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) TimeOutException(nl.nn.adapterframework.core.TimeOutException) ParameterException(nl.nn.adapterframework.core.ParameterException) HtmlCleaner(org.htmlcleaner.HtmlCleaner) URIBuilder(org.apache.http.client.utils.URIBuilder) StatusLine(org.apache.http.StatusLine) StringTokenizer(java.util.StringTokenizer) TimeOutException(nl.nn.adapterframework.core.TimeOutException) SocketTimeoutException(java.net.SocketTimeoutException) MethodNotSupportedException(org.apache.http.MethodNotSupportedException) SenderException(nl.nn.adapterframework.core.SenderException) TagNode(org.htmlcleaner.TagNode)

Aggregations

MethodNotSupportedException (org.apache.http.MethodNotSupportedException)7 ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)4 IOException (java.io.IOException)3 ProtocolException (org.apache.http.ProtocolException)3 UnsupportedHttpVersionException (org.apache.http.UnsupportedHttpVersionException)3 SenderException (nl.nn.adapterframework.core.SenderException)2 TimeOutException (nl.nn.adapterframework.core.TimeOutException)2 ClientProtocolException (org.apache.http.client.ClientProtocolException)2 HttpGet (org.apache.http.client.methods.HttpGet)2 HttpPost (org.apache.http.client.methods.HttpPost)2 HttpRequestBase (org.apache.http.client.methods.HttpRequestBase)2 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 URISyntaxException (java.net.URISyntaxException)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 StringTokenizer (java.util.StringTokenizer)1 GZIPOutputStream (java.util.zip.GZIPOutputStream)1