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:dk.dma.epd.common.prototype.communication.webservice.ShoreHttp.java

public void setRequestBody(byte[] body, String contentType) {
    // TODO if Gzip Compress request
    byte[] compressed = {};
    try {/*  ww  w  .j  a  v a2  s .  c o  m*/
        compressed = Compressor.compress(body);
        //body = compressed;
        //method.addRequestHeader("Content-Encoding", "gzip");
    } catch (IOException e) {
        LOG.error("Failed to GZip request: " + e.getMessage());
    }
    LOG.debug("XML req size           : " + body.length);
    LOG.debug("XML req compressed size: " + compressed.length);
    ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(body, contentType);
    method.setRequestEntity(requestEntity);
}

From source file:com.comcast.cats.service.util.HttpClientUtil.java

public static synchronized Object postForObject(String requestUrl, byte[] payload) {
    Object responseObject = new Object();

    PostMethod httpMethod = new PostMethod(requestUrl);

    InputStream responseStream = null;
    Reader inputStreamReader = null;

    httpMethod.addRequestHeader(VideoRecorderServiceConstants.CONTENT_TYPE,
            VideoRecorderServiceConstants.APPLICATION_XML);

    RequestEntity requestEntity = new ByteArrayRequestEntity(payload, VideoRecorderServiceConstants.UTF);
    httpMethod.setRequestEntity(requestEntity);

    try {/*w w  w  . ja va 2s.co  m*/
        int responseCode = new HttpClient().executeMethod(httpMethod);

        if (HttpStatus.SC_OK != responseCode) {
            logger.error("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.error("[ METHOD   ] " + httpMethod.getName());
            logger.error("[ STATUS   ] " + responseCode);
        } else {
            logger.trace("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.trace("[ METHOD   ] " + httpMethod.getName());
            logger.trace("[ STATUS   ] " + responseCode);
        }

        responseStream = httpMethod.getResponseBodyAsStream();
        inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF);
        responseObject = new Yaml().load(inputStreamReader);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        cleanUp(inputStreamReader, responseStream, httpMethod);
    }

    return responseObject;
}

From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java

public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo);
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);/*from  ww w . j  ava  2s. c  o m*/
    if (null != this.requestPolicy) {
        requestGenerator.setReqPolicy(this.requestPolicy);
    }
    TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP client
    HttpClient httpClient = new HttpClient();
    if (null != this.username) {
        Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    if (null != this.proxyHost) {
        httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
    }

    // create the HTTP POST request
    PostMethod postMethod = new PostMethod(this.tspServiceUrl);
    RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query");
    postMethod.addRequestHeader("User-Agent", this.userAgent);
    postMethod.setRequestEntity(requestEntity);

    // invoke TSP service
    int statusCode = httpClient.executeMethod(postMethod);
    if (HttpStatus.SC_OK != statusCode) {
        LOG.error("Error contacting TSP server " + this.tspServiceUrl);
        throw new Exception("Error contacting TSP server " + this.tspServiceUrl);
    }

    // HTTP input validation
    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
        throw new RuntimeException("missing Content-Type header");
    }
    String contentType = responseContentTypeHeader.getValue();
    if (!contentType.startsWith("application/timestamp-reply")) {
        LOG.debug("response content: " + postMethod.getResponseBodyAsString());
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }
    if (0 == postMethod.getResponseContentLength()) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    InputStream inputStream = postMethod.getResponseBodyAsStream();
    TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream);
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
        LOG.debug("status: " + timeStampResponse.getStatus());
        LOG.debug("status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.debug("fail info int value: " + failInfo.intValue());
            if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) {
                LOG.debug("unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded());
    LOG.debug("signer cert serial number: " + signerCertSerialNumber);
    LOG.debug("signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
            BouncyCastleProvider.PROVIDER_NAME);
    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    X509Certificate signerCert = null;
    Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
    for (Certificate certificate : certificates) {
        X509Certificate x509Certificate = (X509Certificate) certificate;
        if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
            signerCert = x509Certificate;
        }
        String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
        certificateMap.put(ski, x509Certificate);
        LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
    }

    // TSP signer cert path building
    if (null == signerCert) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();

    X509Certificate tsaIssuer = loadCertificate(
            "be/fedict/eid/applet/service/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt");
    X509Certificate rootCA = loadCertificate("be/fedict/eid/applet/service/CA RAIZ NACIONAL COSTA RICA.cer");
    LOG.debug("adding to certificate chain: " + signerCert.getSubjectX500Principal());
    tspCertificateChain.add(signerCert);
    LOG.debug("adding to certificate chain: " + tsaIssuer.getSubjectX500Principal());
    tspCertificateChain.add(tsaIssuer);
    LOG.debug("adding to certificate chain: " + rootCA.getSubjectX500Principal());
    tspCertificateChain.add(rootCA);

    // verify TSP signer signature
    timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME);

    // verify TSP signer certificate
    this.validator.validate(tspCertificateChain, revocationData);

    LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
}

From source file:com.clarkparsia.sbol.editor.sparql.StardogEndpoint.java

private ByteArrayRequestEntity createEntity(Iterable<? extends Statement> theGraph) throws IOException {
    try {//w  w  w.j a va 2 s  .  c o  m
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        RDFWriter writer = Rio.createWriter(RDFFormat.TURTLE, out);
        writer.startRDF();
        for (Statement stmt : theGraph) {
            writer.handleStatement(stmt);
        }
        writer.endRDF();
        return new ByteArrayRequestEntity(out.toByteArray(), RDFFormat.TURTLE.getDefaultMIMEType());
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private HttpResponse executeMethodBytes(EntityEnclosingMethod method, byte[] putBytes, int timeoutMillis)
        throws HttpClientException {
    try {//from   w ww.ja va2 s  . c  om
        method.setRequestEntity(new ByteArrayRequestEntity(putBytes, Constants.APPLICATION_JSON_CONTENT_TYPE));
        method.setRequestHeader(Constants.CONTENT_TYPE_HEADER_NAME, Constants.APPLICATION_OCTET_STREAM_TYPE);
        if (timeoutMillis > 0) {
            return executeWithTimeout(method, timeoutMillis);
        } else {
            return execute(method);
        }
    } catch (Exception e) {
        String trimmedMethodBody = (putBytes.length > JSON_POST_LOG_LENGTH_LIMIT)
                ? new String(putBytes, 0, JSON_POST_LOG_LENGTH_LIMIT)
                : new String(putBytes);
        throw new HttpClientException("Error executing " + method.getName() + " request to:"
                + client.getHostConfiguration().getHostURL() + " path: " + method.getPath() + " byte body: "
                + trimmedMethodBody, e);
    }
}

From source file:com.cordys.coe.ac.httpconnector.impl.StandardRequestHandler.java

/**
 * @see IRequestHandler#process(int, IServerConnection, HttpClient)
 *//*from  w ww  .j ava 2  s  . c  o m*/
@Override
public HttpMethod process(int requestNode, IServerConnection connection, HttpClient httpClient)
        throws HandlerException {
    String uri = getRequestUri(requestNode, connection, httpClient);
    EntityEnclosingMethod httpMethod;

    if (LOG.isDebugEnabled()) {
        LOG.debug("HTTP method is: " + m_method.getHttpMethodType());
    }

    switch (m_method.getHttpMethodType()) {
    case GET:
        HttpMethod httpMethodGet = new GetMethod(uri); // Get method does not have a body. 
        setRequestHeaders(httpMethodGet);
        return httpMethodGet;

    case POST:
        httpMethod = new PostMethod(uri);
        break;

    case PUT:
        httpMethod = new PutMethod(uri);
        break;

    case DELETE:
        HttpMethod httpMethodDelete = new DeleteMethod(uri); // Delete method does not have a body.
        setRequestHeaders(httpMethodDelete);
        return httpMethodDelete;

    default:
        throw new HandlerException(HandlerExceptionMessages.UNKNOWN_HTTP_METHOD);
    }

    int reqNode = requestNode;

    try {
        reqNode = preProcessXml(reqNode, reqNode != requestNode);

        if (xsltNode != 0) {
            reqNode = executeXslt(reqNode, m_method, reqNode != requestNode);
        }

        if (m_requestRootXPath != null) {
            reqNode = handleRequestXPath(reqNode, m_method, reqNode != requestNode);
        }

        if ((m_removeNamespaceUriSet != null) || m_removeAllNamespaces) {
            XmlUtils.removeNamespacesRecursively(reqNode, m_removeNamespaceUriSet);
        }

        reqNode = postProcessXml(reqNode, reqNode != requestNode);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Final Request XML: " + Node.writeToString(reqNode, true));
        }

        // Get the data that should be posted.
        byte[] reqData = getPostData(reqNode, connection);
        String contentType = getContentType();

        httpMethod.setRequestEntity(new ByteArrayRequestEntity(reqData, contentType));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending data: " + new String(reqData));
        }

        httpMethod.setRequestHeader("Content-type", contentType);
        setRequestHeaders(httpMethod);
    } finally {
        if ((reqNode != 0) && (reqNode != requestNode)) {
            Node.delete(reqNode);
            reqNode = 0;
        }
    }

    return httpMethod;
}

From source file:com.zimbra.cs.zimlet.ProxyServlet.java

private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ZimbraLog.clearContext();//  w  w  w. j  a va 2 s .c o m
    boolean isAdmin = isAdminRequest(req);
    AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true)
            : getAuthTokenFromCookie(req, resp, true);
    if (authToken == null) {
        String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
        if (zAuthToken != null) {
            try {
                authToken = AuthProvider.getAuthToken(zAuthToken);
                if (authToken.isExpired()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
                    return;
                }
                if (!authToken.isRegistered()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
                    return;
                }
                if (isAdmin && !authToken.isAdmin()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
                    return;
                }
            } catch (AuthTokenException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
                return;
            }
        }
    }
    if (authToken == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
        return;
    }

    // get the posted body before the server read and parse them.
    byte[] body = copyPostedData(req);

    // sanity check
    String target = req.getParameter(TARGET_PARAM);
    if (target == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // check for permission
    URL url = new URL(target);
    if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // determine whether to return the target inline or store it as an upload
    String uploadParam = req.getParameter(UPLOAD_PARAM);
    boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));

    HttpMethod method = null;
    try {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        String reqMethod = req.getMethod();
        if (reqMethod.equalsIgnoreCase("GET")) {
            method = new GetMethod(target);
        } else if (reqMethod.equalsIgnoreCase("POST")) {
            PostMethod post = new PostMethod(target);
            if (body != null)
                post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = post;
        } else if (reqMethod.equalsIgnoreCase("PUT")) {
            PutMethod put = new PutMethod(target);
            if (body != null)
                put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = put;
        } else if (reqMethod.equalsIgnoreCase("DELETE")) {
            method = new DeleteMethod(target);
        } else {
            ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }

        // handle basic auth
        String auth, user, pass;
        auth = req.getParameter(AUTH_PARAM);
        user = req.getParameter(USER_PARAM);
        pass = req.getParameter(PASS_PARAM);
        if (auth != null && user != null && pass != null) {
            if (!auth.equals(AUTH_BASIC)) {
                ZimbraLog.zimlet.info("unsupported auth type: " + auth);
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            HttpState state = new HttpState();
            state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
            client.setState(state);
            method.setDoAuthentication(true);
        }

        Enumeration headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = (String) headers.nextElement();
            ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
            if (canProxyHeader(hdr)) {
                ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
                if (hdr.equalsIgnoreCase("x-host"))
                    method.getParams().setVirtualHost(req.getHeader(hdr));
                else
                    method.addRequestHeader(hdr, req.getHeader(hdr));
            }
        }

        try {
            if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
                method.setFollowRedirects(true);
            }
            HttpClientUtil.executeMethod(client, method);
        } catch (HttpException ex) {
            ZimbraLog.zimlet.info("exception while proxying " + target, ex);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR
                : method.getStatusCode();

        // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
        Header ctHeader = method.getResponseHeader("Content-Type");
        String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE
                : ctHeader.getValue();

        InputStream targetResponseBody = method.getResponseBodyAsStream();

        if (asUpload) {
            String filename = req.getParameter(FILENAME_PARAM);
            if (filename == null || filename.equals(""))
                filename = new ContentType(contentType).getParameter("name");
            if ((filename == null || filename.equals(""))
                    && method.getResponseHeader("Content-Disposition") != null)
                filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue())
                        .getParameter("filename");
            if (filename == null || filename.equals(""))
                filename = "unknown";

            List<Upload> uploads = null;

            if (targetResponseBody != null) {
                try {
                    Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType,
                            authToken.getAccountId());
                    uploads = Arrays.asList(up);
                } catch (ServiceException e) {
                    if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
                        status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
                    else
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
            }

            resp.setStatus(status);
            FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
        } else {
            resp.setStatus(status);
            resp.setContentType(contentType);
            for (Header h : method.getResponseHeaders())
                if (canProxyHeader(h.getName()))
                    resp.addHeader(h.getName(), h.getValue());
            if (targetResponseBody != null)
                ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:com.zimbra.cs.fb.ExchangeMessage.java

public HttpMethod createMethod(String uri, FreeBusy fb) throws IOException {
    // PROPPATCH/*from w w w.  j a v a 2s  .  c  o  m*/
    PostMethod method = new PostMethod(uri) {
        private String PROPPATCH = "PROPPATCH";

        public String getName() {
            return PROPPATCH;
        }
    };
    Document doc = createRequest(fb);
    byte[] buf = DomUtil.getBytes(doc);
    if (ZimbraLog.fb.isDebugEnabled())
        ZimbraLog.fb.debug(new String(buf, "UTF-8"));
    ByteArrayRequestEntity re = new ByteArrayRequestEntity(buf, "text/xml");
    method.setRequestEntity(re);
    return method;
}

From source file:com.zimbra.cs.fb.ExchangeFreeBusyProvider.java

private boolean formAuth(HttpClient client, ServerInfo info) throws IOException {
    StringBuilder buf = new StringBuilder();
    buf.append("destination=");
    buf.append(URLEncoder.encode(info.url, "UTF-8"));
    buf.append("&username=");
    buf.append(info.authUsername);//from  w  ww .  j  av  a  2s.com
    buf.append("&password=");
    buf.append(URLEncoder.encode(info.authPassword, "UTF-8"));
    buf.append("&flags=0");
    buf.append("&SubmitCreds=Log On");
    buf.append("&trusted=0");
    String url = info.url + LC.calendar_exchange_form_auth_url.value();
    PostMethod method = new PostMethod(url);
    ByteArrayRequestEntity re = new ByteArrayRequestEntity(buf.toString().getBytes(), "x-www-form-urlencoded");
    method.setRequestEntity(re);
    HttpState state = new HttpState();
    client.setState(state);
    try {
        int status = HttpClientUtil.executeMethod(client, method);
        if (status >= 400) {
            ZimbraLog.fb.error("form auth to Exchange returned an error: " + status);
            return false;
        }
    } finally {
        method.releaseConnection();
    }
    return true;
}

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

@Test
public void testPostToSchedulingOutbox() throws Exception {
    Account dav1 = users[1].create();//from   w w w . ja  v a  2 s .  c  om
    Account dav2 = users[2].create();
    Account dav3 = users[3].create();
    String url = getSchedulingOutboxUrl(dav1, dav1);
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    addBasicAuthHeaderForUser(method, dav1);
    method.addRequestHeader("Content-Type", "text/calendar");
    method.addRequestHeader("Originator", "mailto:" + dav1.getName());
    method.addRequestHeader("Recipient", "mailto:" + dav2.getName());
    method.addRequestHeader("Recipient", "mailto:" + dav3.getName());

    method.setRequestEntity(new ByteArrayRequestEntity(exampleCancelIcal(dav1, dav2, dav3).getBytes(),
            MimeConstants.CT_TEXT_CALENDAR));

    HttpMethodExecutor.execute(client, method, HttpStatus.SC_OK);
}