Example usage for org.apache.commons.httpclient.methods ByteArrayRequestEntity ByteArrayRequestEntity

List of usage examples for org.apache.commons.httpclient.methods ByteArrayRequestEntity ByteArrayRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods ByteArrayRequestEntity ByteArrayRequestEntity.

Prototype

public ByteArrayRequestEntity(byte[] paramArrayOfByte, String paramString) 

Source Link

Usage

From source file:com.zimbra.qa.unittest.TestCalDav.java

public static Document delegateForExpandProperty(Account acct) throws IOException, ServiceException {
    ReportMethod method = new ReportMethod(getPrincipalUrl(acct));
    addBasicAuthHeaderForUser(method, acct);
    HttpClient client = new HttpClient();
    TestCalDav.HttpMethodExecutor executor;
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    method.setRequestEntity(//  w  w w  .  ja  va2  s .c  o m
            new ByteArrayRequestEntity(expandPropertyDelegateFor.getBytes(), MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS);
    String respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    Document doc = W3cDomUtil.parseXMLToDoc(respBody);
    org.w3c.dom.Element docElement = doc.getDocumentElement();
    assertEquals("Report node name", DavElements.P_MULTISTATUS, docElement.getLocalName());
    return doc;
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

public static Document setGroupMemberSet(String url, Account acct, Account memberAcct)
        throws IOException, XmlParseException {
    PropPatchMethod method = new PropPatchMethod(url);
    addBasicAuthHeaderForUser(method, acct);
    HttpClient client = new HttpClient();
    TestCalDav.HttpMethodExecutor executor;
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    String body = TestCalDav.propPatchGroupMemberSetTemplate.replace("%%MEMBER%%",
            UrlNamespace.getPrincipalUrl(memberAcct, memberAcct));
    method.setRequestEntity(new ByteArrayRequestEntity(body.getBytes(), MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS);
    String respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    Document doc = W3cDomUtil.parseXMLToDoc(respBody);
    org.w3c.dom.Element docElement = doc.getDocumentElement();
    assertEquals("Report node name", DavElements.P_MULTISTATUS, docElement.getLocalName());
    return doc;/*w  ww. j  a v  a 2s  .  c  o m*/
}

From source file:net.xmind.signin.internal.XMindNetRequest.java

private RequestEntity generateRequestEntity() {
    if (multipart) {
        List<Part> parts = new ArrayList<Part>(params.size());
        for (Parameter param : params) {
            if (param.value instanceof File) {
                try {
                    parts.add(new FilePart(param.name, (File) param.value));
                } catch (FileNotFoundException e) {
                }//w ww  .  j av  a  2  s .  co  m
            } else {
                parts.add(new StringPart(param.name, param.getValue(), "utf-8")); //$NON-NLS-1$
            }
        }
        return new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), method.getParams());
    } else {
        String query = generateQueryString();
        try {
            return new ByteArrayRequestEntity(query.getBytes("utf-8"), DEFAULT_CONTENT_TYPE); //$NON-NLS-1$
        } catch (UnsupportedEncodingException e) {
            //should not happen
        }
    }
    return null;
}

From source file:org.alfresco.httpclient.AbstractHttpClient.java

protected HttpMethod createMethod(Request req) throws IOException {
    StringBuilder url = new StringBuilder(128);
    url.append(baseUrl);/*from  ww w.  j  a va2  s  . c  om*/
    url.append("/service/");
    url.append(req.getFullUri());

    // construct method
    HttpMethod httpMethod = null;
    String method = req.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        GetMethod get = new GetMethod(url.toString());
        httpMethod = get;
        httpMethod.setFollowRedirects(true);
    } else if (method.equalsIgnoreCase("POST")) {
        PostMethod post = new PostMethod(url.toString());
        httpMethod = post;
        ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(req.getBody(), req.getType());
        if (req.getBody().length > DEFAULT_SAVEPOST_BUFFER) {
            post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        }
        post.setRequestEntity(requestEntity);
        // Note: not able to automatically follow redirects for POST, this is handled by sendRemoteRequest
    } else if (method.equalsIgnoreCase("HEAD")) {
        HeadMethod head = new HeadMethod(url.toString());
        httpMethod = head;
        httpMethod.setFollowRedirects(true);
    } else {
        throw new AlfrescoRuntimeException("Http Method " + method + " not supported");
    }

    if (req.getHeaders() != null) {
        for (Map.Entry<String, String> header : req.getHeaders().entrySet()) {
            httpMethod.setRequestHeader(header.getKey(), header.getValue());
        }
    }

    return httpMethod;
}

From source file:org.alfresco.repo.search.impl.solr.SolrQueryHTTPClient.java

protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body)
        throws UnsupportedEncodingException, IOException, HttpException, URIException, JSONException {
    PostMethod post = new PostMethod(url);
    if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER) {
        post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    }/*from   w ww . j  a va  2  s .c  o  m*/
    post.setRequestEntity(new ByteArrayRequestEntity(body.toString().getBytes("UTF-8"), "application/json"));

    try {
        httpClient.executeMethod(post);

        if (post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null) {
                String redirectLocation = locationHeader.getValue();
                post.setURI(new URI(redirectLocation, true));
                httpClient.executeMethod(post);
            }
        }

        if (post.getStatusCode() != HttpServletResponse.SC_OK) {
            throw new LuceneQueryParserException(
                    "Request failed " + post.getStatusCode() + " " + url.toString());
        }

        Reader reader = new BufferedReader(
                new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet()));
        // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
        JSONObject json = new JSONObject(new JSONTokener(reader));

        if (json.has("status")) {
            JSONObject status = json.getJSONObject("status");
            if (status.getInt("code") != HttpServletResponse.SC_OK) {
                throw new LuceneQueryParserException("SOLR side error: " + status.getString("message"));
            }
        }
        return json;
    } finally {
        post.releaseConnection();
    }
}

From source file:org.alfresco.repo.web.scripts.BaseWebScriptTest.java

/**
 * Send Remote Request to stand-alone Web Script Server
 * /*from w w w.ja  va2s  .  com*/
 * @param req Request
 * @param expectedStatus int
 * @return response
 * @throws IOException
 */
protected Response sendRemoteRequest(Request req, int expectedStatus) throws IOException {
    String uri = req.getFullUri();
    if (!uri.startsWith("http")) {
        uri = remoteServer.baseAddress + uri;
    }

    // construct method
    HttpMethod httpMethod = null;
    String method = req.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        GetMethod get = new GetMethod(req.getFullUri());
        httpMethod = get;
    } else if (method.equalsIgnoreCase("POST")) {
        PostMethod post = new PostMethod(req.getFullUri());
        post.setRequestEntity(new ByteArrayRequestEntity(req.getBody(), req.getType()));
        httpMethod = post;
    } else if (method.equalsIgnoreCase("PATCH")) {
        PatchMethod post = new PatchMethod(req.getFullUri());
        post.setRequestEntity(new ByteArrayRequestEntity(req.getBody(), req.getType()));
        httpMethod = post;
    } else if (method.equalsIgnoreCase("PUT")) {
        PutMethod put = new PutMethod(req.getFullUri());
        put.setRequestEntity(new ByteArrayRequestEntity(req.getBody(), req.getType()));
        httpMethod = put;
    } else if (method.equalsIgnoreCase("DELETE")) {
        DeleteMethod del = new DeleteMethod(req.getFullUri());
        httpMethod = del;
    } else {
        throw new AlfrescoRuntimeException("Http Method " + method + " not supported");
    }
    if (req.getHeaders() != null) {
        for (Map.Entry<String, String> header : req.getHeaders().entrySet()) {
            httpMethod.setRequestHeader(header.getKey(), header.getValue());
        }
    }

    // execute method
    httpClient.executeMethod(httpMethod);
    return new HttpMethodResponse(httpMethod);
}

From source file:org.alfresco.rest.api.tests.client.PublicApiHttpClient.java

public HttpResponse post(final RequestContext rq, final String scope, final int version,
        final String entityCollectionName, final Object entityId, final String relationCollectionName,
        final Object relationshipEntityId, final byte[] body, String contentType) throws IOException {
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName,
            entityId, relationCollectionName, relationshipEntityId, null);
    String url = endpoint.getUrl();

    PostMethod req = new PostMethod(url.toString());
    if (body != null) {
        if (contentType == null || contentType.isEmpty()) {
            contentType = "application/octet-stream";
        }/*from   ww  w  .j  a v  a 2  s.  c  o  m*/
        ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(body, contentType);
        req.setRequestEntity(requestEntity);
    }
    return submitRequest(req, rq);
}

From source file:org.anhonesteffort.flock.webdav.caldav.CalDavCollection.java

@Override
protected void putComponentToServer(Calendar calendar, Optional<String> ifMatchETag)
        throws InvalidComponentException, DavException, IOException {
    calendar.getProperties().remove(ProdId.PRODID);
    calendar.getProperties().add(new ProdId(((CalDavStore) getStore()).getProductId()));

    try {/*from w ww  .j av a2  s. c  om*/

        if (Calendars.getUid(calendar) == null)
            throw new InvalidComponentException("Cannot put iCal to server without UID!", false,
                    CalDavConstants.CALDAV_NAMESPACE, getPath());

        String calendarUid = Calendars.getUid(calendar).getValue();
        PutMethod putMethod = new PutMethod(getComponentPathFromUid(calendarUid));

        if (ifMatchETag.isPresent())
            putMethod.addRequestHeader("If-Match", ifMatchETag.get()); // TODO: constant for this.
        else
            putMethod.addRequestHeader("If-None-Match", "*"); // TODO: constant for this.

        try {

            CalendarOutputter calendarOutputter = new CalendarOutputter();
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

            calendarOutputter.output(calendar, byteStream);
            putMethod.setRequestEntity(new ByteArrayRequestEntity(byteStream.toByteArray(),
                    CalDavConstants.HEADER_CONTENT_TYPE_CALENDAR));

            getStore().getClient().execute(putMethod);
            int status = putMethod.getStatusCode();

            if (status == DavServletResponse.SC_REQUEST_ENTITY_TOO_LARGE
                    || status == DavServletResponse.SC_FORBIDDEN) {
                throw new InvalidComponentException("Put method returned bad status " + status, false,
                        CalDavConstants.CALDAV_NAMESPACE, getPath());
            }

            if (status < DavServletResponse.SC_OK || status > DavServletResponse.SC_NO_CONTENT) {
                throw new DavException(status, putMethod.getStatusText());
            }

        } finally {
            putMethod.releaseConnection();
        }

    } catch (ConstraintViolationException e) {
        throw new InvalidComponentException("Caught exception while parsing UID from calendar", false,
                CalDavConstants.CALDAV_NAMESPACE, getPath(), e);
    } catch (ValidationException e) {
        throw new InvalidComponentException("Caught exception whie outputting calendar to stream", false,
                CalDavConstants.CALDAV_NAMESPACE, getPath(), e);
    }
}

From source file:org.anhonesteffort.flock.webdav.carddav.CardDavCollection.java

@Override
protected void putComponentToServer(VCard vCard, Optional<String> ifMatchETag)
        throws IOException, DavException, InvalidComponentException {
    if (vCard.getUid() == null || vCard.getUid().getValue() == null)
        throw new InvalidComponentException("Cannot put a VCard to server without UID!", false,
                CardDavConstants.CARDDAV_NAMESPACE, getPath());

    vCard.getProperties().add(new ProductId(((CardDavStore) getStore()).getProductId()));

    String vCardUid = vCard.getUid().getValue();
    PutMethod putMethod = new PutMethod(getComponentPathFromUid(vCardUid));

    if (ifMatchETag.isPresent())
        putMethod.addRequestHeader("If-Match", ifMatchETag.get()); // TODO: constant for this.
    else//ww  w  .  ja  va2s .c o m
        putMethod.addRequestHeader("If-None-Match", "*"); // TODO: constant for this.

    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    Ezvcard.write(vCard).go(byteStream);

    putMethod.setRequestEntity(
            new ByteArrayRequestEntity(byteStream.toByteArray(), CardDavConstants.HEADER_CONTENT_TYPE_VCARD));

    byteStream = new ByteArrayOutputStream();
    Ezvcard.write(vCard).go(byteStream);

    try {

        getStore().getClient().execute(putMethod);
        int status = putMethod.getStatusCode();

        if (status == DavServletResponse.SC_REQUEST_ENTITY_TOO_LARGE
                || status == DavServletResponse.SC_FORBIDDEN) {
            throw new InvalidComponentException("Put method returned bad status " + status, false,
                    CardDavConstants.CARDDAV_NAMESPACE, getPath());
        }

        if (putMethod.getStatusCode() < DavServletResponse.SC_OK
                || putMethod.getStatusCode() > DavServletResponse.SC_NO_CONTENT) {
            throw new DavException(putMethod.getStatusCode(), putMethod.getStatusText());
        }

    } finally {
        putMethod.releaseConnection();
    }
}

From source file:org.apache.camel.component.http.HttpProducer.java

/**
 * Creates a holder object for the data to send to the remote server.
 *
 * @param exchange the exchange with the IN message with data to send
 * @return the data holder/* w w w  . ja v  a  2 s .c  o m*/
 * @throws CamelExchangeException is thrown if error creating RequestEntity
 */
protected RequestEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
    Message in = exchange.getIn();
    if (in.getBody() == null) {
        return null;
    }

    RequestEntity answer = in.getBody(RequestEntity.class);
    if (answer == null) {
        try {
            Object data = in.getBody();
            if (data != null) {
                String contentType = ExchangeHelper.getContentType(exchange);

                if (contentType != null
                        && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
                    // serialized java object
                    Serializable obj = in.getMandatoryBody(Serializable.class);
                    // write object to output stream
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    HttpHelper.writeObjectToStream(bos, obj);
                    answer = new ByteArrayRequestEntity(bos.toByteArray(),
                            HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
                    IOHelper.close(bos);
                } else if (data instanceof File || data instanceof GenericFile) {
                    // file based (could potentially also be a FTP file etc)
                    File file = in.getBody(File.class);
                    if (file != null) {
                        answer = new FileRequestEntity(file, contentType);
                    }
                } else if (data instanceof String) {
                    // be a bit careful with String as any type can most likely be converted to String
                    // so we only do an instanceof check and accept String if the body is really a String
                    // do not fallback to use the default charset as it can influence the request
                    // (for example application/x-www-form-urlencoded forms being sent)
                    String charset = IOHelper.getCharsetName(exchange, false);
                    answer = new StringRequestEntity((String) data, contentType, charset);
                }
                // fallback as input stream
                if (answer == null) {
                    // force the body as an input stream since this is the fallback
                    InputStream is = in.getMandatoryBody(InputStream.class);
                    answer = new InputStreamRequestEntity(is, contentType);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new CamelExchangeException("Error creating RequestEntity from message body", exchange, e);
        } catch (IOException e) {
            throw new CamelExchangeException("Error serializing message body", exchange, e);
        }
    }
    return answer;
}