Example usage for org.apache.http.entity InputStreamEntity InputStreamEntity

List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity

Introduction

In this page you can find the example usage for org.apache.http.entity InputStreamEntity InputStreamEntity.

Prototype

public InputStreamEntity(InputStream inputStream, ContentType contentType) 

Source Link

Usage

From source file:org.apache.abdera2.common.protocol.Session.java

/**
 * Sends an HTTP POST request to the specified URI.
 * //www  .java  2 s  . co  m
 * @param uri The request URI
 * @param in An InputStream providing the payload of the request
 * @param options The request options
 */
public <T extends ClientResponse> T post(String uri, InputStream in, RequestOptions options) {
    return (T) wrap(execute("POST", uri, new InputStreamEntity(in, -1), options));
}

From source file:com.autonomy.aci.client.services.impl.DocumentProcessorTest.java

@Test
@SuppressWarnings("unchecked")
public void testCheckACIResponseForErrorWithErrorResponse() throws IOException, ProcessorException {
    try {//from  ww w.j av a2 s .  c om
        // Setup with a error response file...
        final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
        response.setEntity(new InputStreamEntity(getClass().getResourceAsStream("/AciException-1.xml"), -1));

        // Set the AciResponseInputStream...
        final AciResponseInputStream stream = new AciResponseInputStreamImpl(response);

        // Process...
        processor.process(stream);
        fail("Should have raised an AciErrorException.");
    } catch (final AciErrorException aee) {
        // Check its properties...
        assertThat("errorId property not as expected.", aee.getErrorId(),
                is(equalTo("AutonomyIDOLServerWOBBLE1")));
        assertThat("errorString property not as expected.", aee.getErrorString(), is(equalTo("ERROR")));
        assertThat("errorDescription property not as expected.", aee.getErrorDescription(),
                is(equalTo("The requested action was not recognised")));
        assertThat("errorCode property not as expected.", aee.getErrorCode(),
                is(equalTo("ERRORNOTIMPLEMENTED")));
        assertThat("errorTime property not as expected.",
                DateFormatUtils.format(aee.getErrorTime(), "dd MMM yy HH:mm:ss"),
                is(equalTo("06 Feb 06 17:03:54")));
    }
}

From source file:com.mwebster.exchange.EasOutboxService.java

/**
 * Send a single message via EAS/* w  w w  .j  a v a2s . c  o  m*/
 * Note that we mark messages SEND_FAILED when there is a permanent failure, rather than an
 * IOException, which is handled by SyncManager with retries, backoffs, etc.
 *
 * @param cacheDir the cache directory for this context
 * @param msgId the _id of the message to send
 * @throws IOException
 */
int sendMessage(File cacheDir, long msgId) throws IOException, MessagingException {
    int result;
    sendCallback(msgId, null, EmailServiceStatus.IN_PROGRESS);
    File tmpFile = File.createTempFile("eas_", "tmp", cacheDir);
    // Write the output to a temporary file
    try {
        String[] cols = getRowColumns(Message.CONTENT_URI, msgId, MessageColumns.FLAGS, MessageColumns.SUBJECT);
        int flags = Integer.parseInt(cols[0]);
        String subject = cols[1];

        boolean reply = (flags & Message.FLAG_TYPE_REPLY) != 0;
        boolean forward = (flags & Message.FLAG_TYPE_FORWARD) != 0;
        // The reference message and mailbox are called item and collection in EAS
        String itemId = null;
        String collectionId = null;
        if (reply || forward) {
            // First, we need to get the id of the reply/forward message
            cols = getRowColumns(Body.CONTENT_URI, BODY_SOURCE_PROJECTION, WHERE_MESSAGE_KEY,
                    new String[] { Long.toString(msgId) });
            if (cols != null) {
                long refId = Long.parseLong(cols[0]);
                // Then, we need the serverId and mailboxKey of the message
                cols = getRowColumns(Message.CONTENT_URI, refId, SyncColumns.SERVER_ID,
                        MessageColumns.MAILBOX_KEY);
                if (cols != null) {
                    itemId = cols[0];
                    long boxId = Long.parseLong(cols[1]);
                    // Then, we need the serverId of the mailbox
                    cols = getRowColumns(Mailbox.CONTENT_URI, boxId, MailboxColumns.SERVER_ID);
                    if (cols != null) {
                        collectionId = cols[0];
                    }
                }
            }
        }

        boolean smartSend = itemId != null && collectionId != null;

        // Write the message in rfc822 format to the temporary file
        FileOutputStream fileStream = new FileOutputStream(tmpFile);
        Rfc822Output.writeTo(mContext, msgId, fileStream, !smartSend, true);
        fileStream.close();

        // Now, get an input stream to our temporary file and create an entity with it
        FileInputStream inputStream = new FileInputStream(tmpFile);
        InputStreamEntity inputEntity = new InputStreamEntity(inputStream, tmpFile.length());

        // Create the appropriate command and POST it to the server
        String cmd = "SendMail&SaveInSent=T";
        if (smartSend) {
            cmd = reply ? "SmartReply" : "SmartForward";
            cmd += "&ItemId=" + itemId + "&CollectionId=" + collectionId + "&SaveInSent=T";
        }
        userLog("Send cmd: " + cmd);
        HttpResponse resp = sendHttpClientPost(cmd, inputEntity, SEND_MAIL_TIMEOUT);

        inputStream.close();
        int code = resp.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            userLog("Deleting message...");
            mContentResolver.delete(ContentUris.withAppendedId(Message.CONTENT_URI, msgId), null, null);
            result = EmailServiceStatus.SUCCESS;
            sendCallback(-1, subject, EmailServiceStatus.SUCCESS);
        } else {
            userLog("Message sending failed, code: " + code);
            ContentValues cv = new ContentValues();
            cv.put(SyncColumns.SERVER_ID, SEND_FAILED);
            Message.update(mContext, Message.CONTENT_URI, msgId, cv);
            // We mark the result as SUCCESS on a non-auth failure since the message itself is
            // already marked failed and we don't want to stop other messages from trying to
            // send.
            if (isAuthError(code)) {
                result = EmailServiceStatus.LOGIN_FAILED;
            } else {
                result = EmailServiceStatus.SUCCESS;
            }
            sendCallback(msgId, null, result);

        }
    } catch (IOException e) {
        // We catch this just to send the callback
        sendCallback(msgId, null, EmailServiceStatus.CONNECTION_ERROR);
        throw e;
    } finally {
        // Clean up the temporary file
        if (tmpFile.exists()) {
            tmpFile.delete();
        }
    }
    return result;
}

From source file:org.elasticsearch.client.RequestLoggerTests.java

public void testTraceResponse() throws IOException {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int statusCode = randomIntBetween(200, 599);
    String reasonPhrase = "REASON";
    BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase);
    String expected = "# " + statusLine.toString();
    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
    int numHeaders = randomIntBetween(0, 3);
    for (int i = 0; i < numHeaders; i++) {
        httpResponse.setHeader("header" + i, "value");
        expected += "\n# header" + i + ": value";
    }/*from   w  w  w . j  a  v a  2s .c om*/
    expected += "\n#";
    boolean hasBody = getRandom().nextBoolean();
    String responseBody = "{\n  \"field\": \"value\"\n}";
    if (hasBody) {
        expected += "\n# {";
        expected += "\n#   \"field\": \"value\"";
        expected += "\n# }";
        HttpEntity entity;
        switch (randomIntBetween(0, 2)) {
        case 0:
            entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON);
            break;
        case 1:
            //test a non repeatable entity
            entity = new InputStreamEntity(
                    new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)),
                    ContentType.APPLICATION_JSON);
            break;
        case 2:
            // Evil entity without a charset
            entity = new StringEntity(responseBody, ContentType.create("application/json", (Charset) null));
            break;
        default:
            throw new UnsupportedOperationException();
        }
        httpResponse.setEntity(entity);
    }
    String traceResponse = RequestLogger.buildTraceResponse(httpResponse);
    assertThat(traceResponse, equalTo(expected));
    if (hasBody) {
        //check that the body is still readable as most entities are not repeatable
        String body = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
        assertThat(body, equalTo(responseBody));
    }
}

From source file:com.android.exchange.EasOutboxService.java

/**
 * Send a single message via EAS//from   w  w w  .  j a v  a2  s.c o m
 * Note that we mark messages SEND_FAILED when there is a permanent failure, rather than an
 * IOException, which is handled by SyncManager with retries, backoffs, etc.
 *
 * @param cacheDir the cache directory for this context
 * @param msgId the _id of the message to send
 * @throws IOException
 */
int sendMessage(File cacheDir, long msgId) throws IOException, MessagingException {
    int result = EmailServiceStatus.SUCCESS;
    sendCallback(msgId, null, EmailServiceStatus.IN_PROGRESS);
    File tmpFile = File.createTempFile("eas_", "tmp", cacheDir);
    // Write the output to a temporary file
    try {
        String[] cols = getRowColumns(Message.CONTENT_URI, msgId, MessageColumns.FLAGS, MessageColumns.SUBJECT);
        int flags = Integer.parseInt(cols[0]);
        String subject = cols[1];

        boolean reply = (flags & Message.FLAG_TYPE_REPLY) != 0;
        boolean forward = (flags & Message.FLAG_TYPE_FORWARD) != 0;
        // The reference message and mailbox are called item and collection in EAS
        String itemId = null;
        String collectionId = null;
        if (reply || forward) {
            // First, we need to get the id of the reply/forward message
            cols = getRowColumns(Body.CONTENT_URI, BODY_SOURCE_PROJECTION, WHERE_MESSAGE_KEY,
                    new String[] { Long.toString(msgId) });
            if (cols != null) {
                long refId = Long.parseLong(cols[0]);
                // Then, we need the serverId and mailboxKey of the message
                cols = getRowColumns(Message.CONTENT_URI, refId, SyncColumns.SERVER_ID,
                        MessageColumns.MAILBOX_KEY);
                if (cols != null) {
                    itemId = cols[0];
                    long boxId = Long.parseLong(cols[1]);
                    // Then, we need the serverId of the mailbox
                    cols = getRowColumns(Mailbox.CONTENT_URI, boxId, MailboxColumns.SERVER_ID);
                    if (cols != null) {
                        collectionId = cols[0];
                    }
                }
            }
        }

        boolean smartSend = itemId != null && collectionId != null;

        // Write the message in rfc822 format to the temporary file
        FileOutputStream fileStream = new FileOutputStream(tmpFile);
        Rfc822Output.writeTo(mContext, msgId, fileStream, !smartSend, true);
        fileStream.close();

        // Now, get an input stream to our temporary file and create an entity with it
        FileInputStream inputStream = new FileInputStream(tmpFile);
        InputStreamEntity inputEntity = new InputStreamEntity(inputStream, tmpFile.length());

        // Create the appropriate command and POST it to the server
        String cmd = "SendMail&SaveInSent=T";
        if (smartSend) {
            cmd = reply ? "SmartReply" : "SmartForward";
            cmd += "&ItemId=" + itemId + "&CollectionId=" + collectionId + "&SaveInSent=T";
        }
        userLog("Send cmd: " + cmd);
        HttpResponse resp = sendHttpClientPost(cmd, inputEntity, SEND_MAIL_TIMEOUT);

        inputStream.close();
        int code = resp.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            userLog("Deleting message...");
            mContentResolver.delete(ContentUris.withAppendedId(Message.CONTENT_URI, msgId), null, null);
            result = EmailServiceStatus.SUCCESS;
            sendCallback(-1, subject, EmailServiceStatus.SUCCESS);
        } else {
            userLog("Message sending failed, code: " + code);

            boolean retrySuccess = false;
            if (smartSend) {
                userLog("Retrying without smartSend");
                cmd = "SendMail&SaveInSent=T";
                userLog("Send cmd: " + cmd);

                inputStream = new FileInputStream(tmpFile);
                inputEntity = new InputStreamEntity(inputStream, tmpFile.length());

                resp = sendHttpClientPost(cmd, inputEntity, SEND_MAIL_TIMEOUT);

                inputStream.close();
                code = resp.getStatusLine().getStatusCode();
                if (code == HttpStatus.SC_OK) {
                    userLog("Deleting message...");
                    mContentResolver.delete(ContentUris.withAppendedId(Message.CONTENT_URI, msgId), null, null);
                    result = EmailServiceStatus.SUCCESS;
                    sendCallback(-1, subject, EmailServiceStatus.SUCCESS);
                    retrySuccess = true;
                }
            }

            if (!retrySuccess) {
                userLog("Message sending failed, code: " + code);

                ContentValues cv = new ContentValues();
                cv.put(SyncColumns.SERVER_ID, SEND_FAILED);
                Message.update(mContext, Message.CONTENT_URI, msgId, cv);
                // We mark the result as SUCCESS on a non-auth failure since the message itself
                // is already marked failed and we don't want to stop other messages from
                // trying to send.
                if (isAuthError(code)) {
                    result = EmailServiceStatus.LOGIN_FAILED;
                } else {
                    result = EmailServiceStatus.SUCCESS;
                }
                sendCallback(msgId, null, result);
            }

        }
    } catch (IOException e) {
        // We catch this just to send the callback
        sendCallback(msgId, null, EmailServiceStatus.CONNECTION_ERROR);
        throw e;
    } finally {
        // Clean up the temporary file
        if (tmpFile.exists()) {
            tmpFile.delete();
        }
    }
    return result;
}

From source file:eu.scape_project.fcrepo.integration.ReferencedContentIntellectualEntitiesIT.java

@Test
public void testIngestIntellectualEntitiesAsyncWithSameIDs() throws Exception {
    List<String> entityIds = new ArrayList(Arrays.asList("ref-async-6", "ref-async-6"));
    List<String> queueId = new ArrayList<>();
    int count = 0;
    for (String id : entityIds) {
        IntellectualEntity ie = TestUtil.createTestEntityWithMultipleRepresentations(id);
        HttpPost post = new HttpPost(SCAPE_URL + "/entity-async");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(ie, sink);
        post.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size()));
        HttpResponse resp = this.client.execute(post);
        if (count++ == 0) {
            assertEquals(200, resp.getStatusLine().getStatusCode());
        } else {/*  w  w w. j  ava  2 s .c  o  m*/
            assertEquals(500, resp.getStatusLine().getStatusCode());
        }
        post.releaseConnection();
    }

}

From source file:se.inera.certificate.proxy.mappings.remote.RemoteDispatcher.java

private HttpResponse makePostRequest(HttpServletRequest request, HttpPost post) throws IOException {
    addHeaders(request, post);/*from  w w  w  . ja  v  a  2  s  .c  o  m*/
    post.setEntity(new InputStreamEntity(request.getInputStream(), -1));
    return makeRequest(post);
}

From source file:org.deegree.protocol.ows.http.OwsHttpClientImpl.java

@Override
public OwsHttpResponse doPost(URL endPoint, String contentType, StreamBufferStore body,
        Map<String, String> headers) throws IOException {

    OwsHttpResponse response = null;/*from   w  ww.ja  va2  s.  c o m*/
    try {
        HttpPost httpPost = new HttpPost(endPoint.toURI());
        DefaultHttpClient httpClient = getInitializedHttpClient(endPoint);
        LOG.debug("Performing POST request on " + endPoint);
        LOG.debug("post size: " + body.size());
        InputStreamEntity entity = new InputStreamEntity(body.getInputStream(), (long) body.size());
        entity.setContentType(contentType);
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        response = new OwsHttpResponseImpl(httpResponse, httpClient.getConnectionManager(),
                endPoint.toString());
    } catch (Throwable e) {
        String msg = "Error performing POST request on '" + endPoint + "': " + e.getMessage();
        throw new IOException(msg);
    }
    return response;
}

From source file:com.google.acre.servlet.ProxyPassServlet.java

/**
 * Sets up the given {@link PostMethod} to send the same standard POST
 * data as was sent in the given {@link HttpServletRequest}
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                                configuring to send a standard POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains
 *                            the POST data to be sent via the {@link PostMethod}
 *//*  w  ww.  j  av a 2 s  .  co  m*/
private void handleStandardPost(HttpPost postMethodProxyRequest, HttpServletRequest hsr) throws IOException {
    HttpEntity re = new InputStreamEntity(hsr.getInputStream(), hsr.getContentLength());
    postMethodProxyRequest.setEntity(re);
}