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) 

Source Link

Usage

From source file:eu.learnpad.core.impl.qm.XwikiBridgeInterfaceRestResource.java

private String localGenerateQuestionnaires(String modelSetId, String type, byte[] configurationFile)
        throws LpRestExceptionXWikiImpl {
    // Ask the QM to generate new questionnaire for a given model set
    // that has been already imported
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/qm/bridge/generate/%s", DefaultRestResource.REST_URI, modelSetId);
    PostMethod postMethod = new PostMethod(uri);

    NameValuePair[] queryString = new NameValuePair[1];
    queryString[0] = new NameValuePair("type", type);
    postMethod.setQueryString(queryString);

    RequestEntity requestEntity = null;/*from ww  w . j a  v  a 2  s .  co m*/
    if (configurationFile != null) {
        postMethod.addRequestHeader("Content-Type", "application/octet-stream");
        requestEntity = new ByteArrayRequestEntity(configurationFile);
    }
    postMethod.setRequestEntity(requestEntity);

    String genProcessID = null;
    try {
        httpClient.executeMethod(postMethod);
        genProcessID = postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
    return genProcessID;
}

From source file:com.zimbra.cs.dav.service.DavMethod.java

public HttpMethod toHttpMethod(DavContext ctxt, String targetUrl) throws IOException, DavException {
    if (ctxt.getUpload() != null && ctxt.getUpload().getSize() > 0) {
        PostMethod method = new PostMethod(targetUrl) {
            @Override//from  www  . j  a  v a 2s  . co m
            public String getName() {
                return getMethodName();
            }
        };
        RequestEntity reqEntry;
        if (ctxt.hasRequestMessage()) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLWriter writer = new XMLWriter(baos);
            writer.write(ctxt.getRequestMessage());
            reqEntry = new ByteArrayRequestEntity(baos.toByteArray());
        } else { // this could be a huge upload
            reqEntry = new InputStreamRequestEntity(ctxt.getUpload().getInputStream(),
                    ctxt.getUpload().getSize());
        }
        method.setRequestEntity(reqEntry);
        return method;
    }
    return new GetMethod(targetUrl) {
        @Override
        public String getName() {
            return getMethodName();
        }
    };
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.WsdlPackagingRequestFilter.java

protected String initWsdlRequest(WsdlRequest wsdlRequest, ExtendedPostMethod postMethod, String requestContent)
        throws Exception {
    MimeMultipart mp = null;//from ww w  .  ja  v  a 2  s .  co  m

    StringToStringMap contentIds = new StringToStringMap();
    boolean isXOP = wsdlRequest.isMtomEnabled() && wsdlRequest.isForceMtom();

    // preprocess only if neccessary
    if (wsdlRequest.isMtomEnabled() || wsdlRequest.isInlineFilesEnabled()
            || wsdlRequest.getAttachmentCount() > 0) {
        try {
            mp = new MimeMultipart();

            MessageXmlObject requestXmlObject = new MessageXmlObject(wsdlRequest.getOperation(), requestContent,
                    true);
            MessageXmlPart[] requestParts = requestXmlObject.getMessageParts();
            for (MessageXmlPart requestPart : requestParts) {
                if (AttachmentUtils.prepareMessagePart(wsdlRequest, mp, requestPart, contentIds))
                    isXOP = true;
            }
            requestContent = requestXmlObject.getMessageContent();
        } catch (Throwable e) {
            SoapUI.log.warn("Failed to process inline/MTOM attachments; " + e);
        }
    }

    // non-multipart request?
    if (!isXOP && (mp == null || mp.getCount() == 0) && hasContentAttachmentsOnly(wsdlRequest)) {
        String encoding = System.getProperty("soapui.request.encoding",
                StringUtils.unquote(wsdlRequest.getEncoding()));
        byte[] content = StringUtils.isNullOrEmpty(encoding) ? requestContent.getBytes()
                : requestContent.getBytes(encoding);
        postMethod.setRequestEntity(new ByteArrayRequestEntity(content));
    } else {
        // make sure..
        if (mp == null)
            mp = new MimeMultipart();

        // init root part
        initRootPart(wsdlRequest, requestContent, mp, isXOP);

        // init mimeparts
        AttachmentUtils.addMimeParts(wsdlRequest, Arrays.asList(wsdlRequest.getAttachments()), mp, contentIds);

        // create request message
        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(mp);
        message.saveChanges();
        WsdlRequestMimeMessageRequestEntity mimeMessageRequestEntity = new WsdlRequestMimeMessageRequestEntity(
                message, isXOP, wsdlRequest);
        postMethod.setRequestEntity(mimeMessageRequestEntity);
        postMethod.setRequestHeader("Content-Type", mimeMessageRequestEntity.getContentType());
        postMethod.setRequestHeader("MIME-Version", "1.0");
    }

    return requestContent;
}

From source file:com.mindquarry.common.index.SolrIndexClient.java

private void sendToIndexer(byte[] content) throws Exception {
    PostMethod pMethod = new PostMethod(solrEndpoint);
    pMethod.setDoAuthentication(true);//from  w ww  .  ja v a  2 s.c  om
    pMethod.addRequestHeader("accept", "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$
    pMethod.setRequestEntity(new ByteArrayRequestEntity(content));

    try {
        httpClient.executeMethod(pMethod);
    } finally {
        pMethod.releaseConnection();
    }

    if (pMethod.getStatusCode() == 200) {
        // everything worked fine, nothing more to do
    } else if (pMethod.getStatusCode() == 401) {
        getLogger().warn("Authorization problem. Could not connect to index updater.");
    } else {
        System.out.println("Unknown error");
        System.out.println("STATUS: " + pMethod.getStatusCode());
        System.out.println("RESPONSE: " + pMethod.getResponseBodyAsString());
    }
    pMethod.releaseConnection();
}

From source file:CertStreamCallback.java

private static void invokeActions(String url, String params, byte[] data, Part[] parts, String accept,
        String contentType, String sessionID, String language, String method, Callback callback) {

    if (params != null && !"".equals(params)) {
        if (url.contains("?")) {
            url = url + "&" + params;
        } else {/*  w  w w . j a  v a  2s  .  c  om*/
            url = url + "?" + params;
        }
    }

    if (language != null && !"".equals(language)) {
        if (url.contains("?")) {
            url = url + "&language=" + language;
        } else {
            url = url + "?language=" + language;
        }
    }

    HttpMethod httpMethod = null;

    try {
        HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        httpMethod = getHttpMethod(url, method);
        if ((httpMethod instanceof PostMethod) || (httpMethod instanceof PutMethod)) {
            if (null != data)
                ((EntityEnclosingMethod) httpMethod).setRequestEntity(new ByteArrayRequestEntity(data));
            if (httpMethod instanceof PostMethod && null != parts)
                ((PostMethod) httpMethod)
                        .setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams()));
        }

        if (sessionID != null) {
            httpMethod.addRequestHeader("Cookie", "JSESSIONID=" + sessionID);
        }

        if (!(httpMethod instanceof PostMethod && null != parts)) {
            if (null != accept && !"".equals(accept))
                httpMethod.addRequestHeader("Accept", accept);
            if (null != contentType && !"".equals(contentType))
                httpMethod.addRequestHeader("Content-Type", contentType);
        }

        int statusCode = httpClient.executeMethod(httpMethod);
        if (statusCode != HttpStatus.SC_OK) {
            throw ActionException.create(ClientMessages.CON_ERROR1, httpMethod.getStatusLine());
        }

        contentType = null != httpMethod.getResponseHeader("Content-Type")
                ? httpMethod.getResponseHeader("Content-Type").getValue()
                : accept;

        InputStream o = httpMethod.getResponseBodyAsStream();
        if (callback != null) {
            callback.execute(o, contentType, sessionID);
        }

    } catch (Exception e) {
        String result = BizClientUtils.doError(e, contentType);
        ByteArrayInputStream in = null;
        try {
            in = new ByteArrayInputStream(result.getBytes("UTF-8"));
            if (callback != null) {
                callback.execute(in, contentType, null);
            }

        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1.getMessage() + "", e1);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    } finally {
        // 
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:ch.flatland.cdo.client.internal.http.HTTPSClientConnector.java

private void request(ExtendedIOHandler handler) throws IOException, HttpException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ExtendedDataOutputStream out = new ExtendedDataOutputStream(baos);
    handler.handleOut(out);/* w w  w . ja  v a2s.  com*/
    out.flush();

    PostMethod method = createHTTPMethod(url);
    method.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));

    try {
        httpClient.executeMethod(method);
        InputStream bodyInputStream = method.getResponseBodyAsStream();
        ExtendedDataInputStream in = new ExtendedDataInputStream(bodyInputStream);
        handler.handleIn(in);

    } finally {
        method.releaseConnection();
    }
}

From source file:com.example.listsync.WebDavRepository.java

private void doUpload(String file, List<String> content) throws IOException {
    LOGGER.info("uploading {}", file);
    LOGGER.info("uploading {} -> {}", file, content);
    PutMethod putMethod = new PutMethod(config.getBaseUrl() + config.getWatchpath() + file);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    IOUtils.writeLines(content, IOUtils.LINE_SEPARATOR_UNIX, output);
    putMethod.setRequestEntity(new ByteArrayRequestEntity(output.toByteArray()));
    int code = client.executeMethod(putMethod);
    LOGGER.info("upload resultcode: {}", code);
}

From source file:com.mindquarry.search.serializer.IndexPostSerializer.java

@Override
public void endDocument() throws SAXException {
    super.endDocument();

    Node node = this.res.getNode();
    Element root = (Element) ((Document) node).getFirstChild();
    String action = root.getAttribute("action"); //$NON-NLS-1$

    NodeList children = root.getChildNodes();

    if (true) { // should resolve the action and find out wether it is a
        // cycle through all children of the root element
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            // for every child element...
            if (child instanceof Element) {

                // block source which can be posted by creating a new
                // servlet request
                URL url = null;/*  w  w  w . ja v  a 2s .c  om*/
                try {
                    url = new URL(action);
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                }
                HttpClient client = new HttpClient();
                client.getState().setCredentials(
                        new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
                        new UsernamePasswordCredentials(login, password));

                PostMethod pMethod = new PostMethod(action);
                pMethod.setDoAuthentication(true);
                pMethod.addRequestHeader("accept", "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                TransformerFactory tf = TransformerFactory.newInstance();
                try {
                    tf.newTransformer().transform(new DOMSource(child), new StreamResult(baos));
                    pMethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
                    client.executeMethod(pMethod);
                } catch (TransformerConfigurationException e) {
                    getLogger().error("Failed to configure transformer prior to posting", e);
                } catch (TransformerException e) {
                    getLogger().error("Failed to transform prior to posting", e);
                } catch (HttpException e) {
                    getLogger().error("Failed to post", e);
                } catch (IOException e) {
                    getLogger().error("Something went wrong", e);
                }
            }
        }
    }
}

From source file:jp.primecloud.auto.zabbix.ZabbixAccessor.java

protected String post(String jsonRequest) {
    PostMethod postMethod = new PostMethod(apiUrl);
    postMethod.setRequestHeader("Content-Type", "application/json-rpc");
    postMethod.setRequestEntity(new ByteArrayRequestEntity(jsonRequest.getBytes()));

    int status;//  w w  w .j ava 2s.  co m
    try {
        status = httpClient.executeMethod(postMethod);
    } catch (HttpException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (status < 200 || status >= 300) {
        String body;
        try {
            body = postMethod.getResponseBodyAsString();
        } catch (Exception ignore) {
            body = "";
        }
        throw new RuntimeException("Reponse Error: status=" + status + ", body=" + body);
    }

    String jsonResponse;
    try {
        jsonResponse = postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return jsonResponse;
}

From source file:net.jadler.JadlerStubbingIntegrationTest.java

@Test
public void havingRawBody() throws IOException {
    onRequest().havingRawBodyEqualTo(BINARY_BODY).respond().withStatus(201);

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new ByteArrayRequestEntity(BINARY_BODY));

    final int status = client.executeMethod(method);
    assertThat(status, is(201));/*ww  w  . ja va  2s  .  c  o  m*/
}