Search in sources :

Example 6 with HttpEntity

use of org.openecard.apache.http.HttpEntity in project open-ecard by ecsec.

the class StreamHttpClientConnection method sendRequestEntity.

@Override
public void sendRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException {
    assertOpen();
    final HttpEntity entity = request.getEntity();
    if (entity == null) {
        return;
    }
    final OutputStream outstream = prepareOutput(request);
    entity.writeTo(outstream);
    outstream.close();
}
Also used : HttpEntity(org.openecard.apache.http.HttpEntity) BasicHttpEntity(org.openecard.apache.http.entity.BasicHttpEntity) ContentLengthOutputStream(org.openecard.apache.http.impl.io.ContentLengthOutputStream) IdentityOutputStream(org.openecard.apache.http.impl.io.IdentityOutputStream) ChunkedOutputStream(org.openecard.apache.http.impl.io.ChunkedOutputStream) OutputStream(java.io.OutputStream)

Example 7 with HttpEntity

use of org.openecard.apache.http.HttpEntity in project open-ecard by ecsec.

the class PAOS method sendStartPAOS.

/**
 * Sends start PAOS and answers all successor messages to the server associated with this instance.
 * Messages are exchanged until the server replies with a {@code StartPAOSResponse} message.
 *
 * @param message The StartPAOS message which is sent in the first message.
 * @return The {@code StartPAOSResponse} message from the server.
 * @throws DispatcherException In case there errors with the message conversion or the dispatcher.
 * @throws PAOSException In case there were errors in the transport layer.
 * @throws PAOSConnectionException
 */
public StartPAOSResponse sendStartPAOS(StartPAOS message) throws DispatcherException, PAOSException, PAOSConnectionException {
    Object msg = message;
    StreamHttpClientConnection conn = null;
    HttpContext ctx = new BasicHttpContext();
    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    DefaultConnectionReuseStrategy reuse = new DefaultConnectionReuseStrategy();
    boolean connectionDropped = false;
    ResponseBaseType lastResponse = null;
    try {
        // loop and send makes a computer happy
        while (true) {
            // set up connection to PAOS endpoint
            // if this one fails we may not continue
            conn = openHttpStream();
            boolean isReusable;
            // send as long as connection is valid
            try {
                do {
                    // save the last message we sent to the eID-Server.
                    if (msg instanceof ResponseBaseType) {
                        lastResponse = (ResponseBaseType) msg;
                    }
                    // prepare request
                    String resource = tlsHandler.getResource();
                    BasicHttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("POST", resource);
                    HttpRequestHelper.setDefaultHeader(req, tlsHandler.getServerAddress());
                    req.setHeader(HEADER_KEY_PAOS, headerValuePaos);
                    req.setHeader("Accept", "text/xml, application/xml, application/vnd.paos+xml");
                    ContentType reqContentType = ContentType.create("application/vnd.paos+xml", "UTF-8");
                    HttpUtils.dumpHttpRequest(LOG, "before adding content", req);
                    String reqMsgStr = createPAOSResponse(msg);
                    StringEntity reqMsg = new StringEntity(reqMsgStr, reqContentType);
                    req.setEntity(reqMsg);
                    req.setHeader(reqMsg.getContentType());
                    req.setHeader("Content-Length", Long.toString(reqMsg.getContentLength()));
                    // send request and receive response
                    LOG.debug("Sending HTTP request.");
                    HttpResponse response = httpexecutor.execute(req, conn, ctx);
                    LOG.debug("HTTP response received.");
                    int statusCode = response.getStatusLine().getStatusCode();
                    try {
                        checkHTTPStatusCode(statusCode);
                    } catch (PAOSConnectionException ex) {
                        // response with error. So check the status of our last response to the eID-Server
                        if (lastResponse != null) {
                            WSHelper.checkResult(lastResponse);
                        }
                        throw ex;
                    }
                    conn.receiveResponseEntity(response);
                    HttpEntity entity = response.getEntity();
                    byte[] entityData = FileUtils.toByteArray(entity.getContent());
                    HttpUtils.dumpHttpResponse(LOG, response, entityData);
                    // consume entity
                    Object requestObj = processPAOSRequest(new ByteArrayInputStream(entityData));
                    // break when message is startpaosresponse
                    if (requestObj instanceof StartPAOSResponse) {
                        StartPAOSResponse startPAOSResponse = (StartPAOSResponse) requestObj;
                        // an ok.
                        if (lastResponse != null) {
                            WSHelper.checkResult(lastResponse);
                        }
                        WSHelper.checkResult(startPAOSResponse);
                        return startPAOSResponse;
                    }
                    // send via dispatcher
                    msg = dispatcher.deliver(requestObj);
                    // check if connection can be used one more time
                    isReusable = reuse.keepAlive(response, ctx);
                    connectionDropped = false;
                } while (isReusable);
            } catch (IOException ex) {
                if (!connectionDropped) {
                    connectionDropped = true;
                    LOG.warn("PAOS server closed the connection. Trying to connect again.");
                } else {
                    String errMsg = "Error in the link to the PAOS server.";
                    LOG.error(errMsg);
                    throw new PAOSException(DELIVERY_FAILED, ex);
                }
            }
        }
    } catch (HttpException ex) {
        throw new PAOSException(DELIVERY_FAILED, ex);
    } catch (SOAPException ex) {
        throw new PAOSException(SOAP_MESSAGE_FAILURE, ex);
    } catch (MarshallingTypeException ex) {
        throw new PAOSDispatcherException(MARSHALLING_ERROR, ex);
    } catch (InvocationTargetException ex) {
        throw new PAOSDispatcherException(DISPATCHER_ERROR, ex);
    } catch (TransformerException ex) {
        throw new DispatcherException(ex);
    } catch (WSException ex) {
        throw new PAOSException(ex);
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (IOException ex) {
        // throw new PAOSException(ex);
        }
    }
}
Also used : MarshallingTypeException(org.openecard.ws.marshal.MarshallingTypeException) HttpRequestExecutor(org.openecard.apache.http.protocol.HttpRequestExecutor) ContentType(org.openecard.apache.http.entity.ContentType) HttpEntity(org.openecard.apache.http.HttpEntity) BasicHttpContext(org.openecard.apache.http.protocol.BasicHttpContext) DefaultConnectionReuseStrategy(org.openecard.apache.http.impl.DefaultConnectionReuseStrategy) StartPAOSResponse(iso.std.iso_iec._24727.tech.schema.StartPAOSResponse) StreamHttpClientConnection(org.openecard.transport.httpcore.StreamHttpClientConnection) StringEntity(org.openecard.apache.http.entity.StringEntity) SOAPException(org.openecard.ws.soap.SOAPException) WSException(org.openecard.common.WSHelper.WSException) HttpException(org.openecard.apache.http.HttpException) TransformerException(javax.xml.transform.TransformerException) BasicHttpEntityEnclosingRequest(org.openecard.apache.http.message.BasicHttpEntityEnclosingRequest) BasicHttpContext(org.openecard.apache.http.protocol.BasicHttpContext) HttpContext(org.openecard.apache.http.protocol.HttpContext) HttpResponse(org.openecard.apache.http.HttpResponse) DispatcherException(org.openecard.common.interfaces.DispatcherException) ResponseBaseType(oasis.names.tc.dss._1_0.core.schema.ResponseBaseType) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 8 with HttpEntity

use of org.openecard.apache.http.HttpEntity in project open-ecard by ecsec.

the class HttpAppPluginActionHandler method getRequestBody.

private RequestBody getRequestBody(HttpRequest httpRequest, String resourceName) throws IOException {
    try {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) httpRequest;
        HttpEntity entity = entityRequest.getEntity();
        InputStream is = entity.getContent();
        // TODO: This assumes the content is UTF-8. Evaluate what is actually sent.
        String value = FileUtils.toString(is);
        String mimeType = ContentType.get(entity).getMimeType();
        // TODO: find out if we have a Base64 coded value
        boolean base64Content = false;
        RequestBody body = new RequestBody(resourceName, null);
        body.setValue(value, mimeType, base64Content);
        return body;
    } catch (UnsupportedCharsetException | ParseException e) {
        LOG.error("Failed to create request body.", e);
    }
    return null;
}
Also used : HttpEntity(org.openecard.apache.http.HttpEntity) InputStream(java.io.InputStream) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) HttpEntityEnclosingRequest(org.openecard.apache.http.HttpEntityEnclosingRequest) ParseException(org.openecard.apache.http.ParseException) RequestBody(org.openecard.addon.bind.RequestBody)

Example 9 with HttpEntity

use of org.openecard.apache.http.HttpEntity in project open-ecard by ecsec.

the class ChipGateway method sendMessage.

private <T> T sendMessage(String resource, String msg, Class<T> resClass, boolean tryAgain) throws ConnectionError, InvalidRedirectUrlException, ChipGatewayDataError {
    try {
        // open initial connection
        if (conn == null || !canReuse || (!conn.isOpen() && canReuse)) {
            openHttpStream();
        }
        // prepare request
        BasicHttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("POST", resource);
        HttpRequestHelper.setDefaultHeader(req, tlsHandler.getServerAddress());
        req.setHeader("Accept", "application/json");
        ContentType reqContentType = ContentType.create("application/json", "UTF-8");
        if (LOG_HTTP_MESSAGES) {
            HttpUtils.dumpHttpRequest(LOG, "before adding content", req);
        }
        StringEntity reqMsg = new StringEntity(msg, reqContentType);
        req.setEntity(reqMsg);
        req.setHeader(reqMsg.getContentType());
        req.setHeader("Content-Length", Long.toString(reqMsg.getContentLength()));
        if (LOG_HTTP_MESSAGES) {
            LOG.debug(msg);
        }
        // send request and receive response
        LOG.debug("Sending HTTP request.");
        HttpResponse response = httpExecutor.execute(req, conn, httpCtx);
        canReuse = reuseStrategy.keepAlive(response, httpCtx);
        LOG.debug("HTTP response received.");
        int statusCode = response.getStatusLine().getStatusCode();
        checkHTTPStatusCode(statusCode);
        conn.receiveResponseEntity(response);
        HttpEntity entity = response.getEntity();
        byte[] entityData = FileUtils.toByteArray(entity.getContent());
        if (LOG_HTTP_MESSAGES) {
            HttpUtils.dumpHttpResponse(LOG, response, entityData);
        }
        // convert entity and return it
        T resultObj = parseResultObj(entityData, resClass);
        return resultObj;
    } catch (IOException ex) {
        if (!Thread.currentThread().isInterrupted() && tryAgain) {
            String errorMsg = "ChipGateway server closed the connection. Trying to connect again.";
            if (LOG.isDebugEnabled()) {
                LOG.debug(errorMsg, ex);
            } else {
                LOG.info(errorMsg);
            }
            canReuse = false;
            return sendMessage(resource, msg, resClass, false);
        } else {
            throw new ConnectionError(token.finalizeErrorAddress(ResultMinor.COMMUNICATION_ERROR), CONNECTION_OPEN_FAILED, ex);
        }
    } catch (HttpException ex) {
        throw new ConnectionError(token.finalizeErrorAddress(ResultMinor.SERVER_ERROR), HTTP_ERROR, ex);
    }
}
Also used : StringEntity(org.openecard.apache.http.entity.StringEntity) ContentType(org.openecard.apache.http.entity.ContentType) HttpEntity(org.openecard.apache.http.HttpEntity) ConnectionError(org.openecard.addons.cg.ex.ConnectionError) HttpResponse(org.openecard.apache.http.HttpResponse) HttpException(org.openecard.apache.http.HttpException) IOException(java.io.IOException) BasicHttpEntityEnclosingRequest(org.openecard.apache.http.message.BasicHttpEntityEnclosingRequest)

Aggregations

HttpEntity (org.openecard.apache.http.HttpEntity)9 HttpResponse (org.openecard.apache.http.HttpResponse)5 BasicHttpEntityEnclosingRequest (org.openecard.apache.http.message.BasicHttpEntityEnclosingRequest)4 BasicHttpContext (org.openecard.apache.http.protocol.BasicHttpContext)4 HttpContext (org.openecard.apache.http.protocol.HttpContext)4 HttpRequestExecutor (org.openecard.apache.http.protocol.HttpRequestExecutor)4 IOException (java.io.IOException)3 Header (org.openecard.apache.http.Header)3 HttpException (org.openecard.apache.http.HttpException)3 DefaultConnectionReuseStrategy (org.openecard.apache.http.impl.DefaultConnectionReuseStrategy)3 StreamHttpClientConnection (org.openecard.transport.httpcore.StreamHttpClientConnection)3 InputStream (java.io.InputStream)2 OutputStream (java.io.OutputStream)2 BasicHttpEntity (org.openecard.apache.http.entity.BasicHttpEntity)2 ContentType (org.openecard.apache.http.entity.ContentType)2 StringEntity (org.openecard.apache.http.entity.StringEntity)2 TlsClientProtocol (org.openecard.bouncycastle.tls.TlsClientProtocol)2 StartPAOSResponse (iso.std.iso_iec._24727.tech.schema.StartPAOSResponse)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1