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:org.pentaho.di.sdk.samples.carte.RegisterSlaveSample.java

public static void sendRegisterSlaveRequest(String urlString, String authentication, String xml)
        throws Exception {
    PostMethod method = new PostMethod(urlString);
    method.setRequestEntity(new ByteArrayRequestEntity(xml.getBytes("UTF-8")));
    method.setDoAuthentication(true);/*from  w w  w.java 2  s . c  o m*/
    //adding authorization token
    if (authentication != null) {
        method.addRequestHeader(new Header("Authorization", authentication));
    }

    //executing method
    HttpClient client = new HttpClient();
    int code = client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    method.releaseConnection();
    if (code >= 400) {
        System.out.println("Error occurred during registering slave.");
    }
    System.out.println("Server response:");
    System.out.println(response);
}

From source file:org.pentaho.di.sdk.samples.carte.RegisterTransSample.java

public static String addTransToServlet(String urlString, String xml, String authentication) throws Exception {
    PostMethod method = new PostMethod(urlString);
    method.setRequestEntity(new ByteArrayRequestEntity(xml.getBytes("UTF-8")));
    method.setDoAuthentication(true);//from w  w  w  .ja  v  a 2  s.  c  o m
    method.addRequestHeader(new Header("Content-Type", "text/xml;charset=UTF-8"));
    //adding authorization token
    if (authentication != null) {
        method.addRequestHeader(new Header("Authorization", authentication));
    }

    //executing method
    HttpClient client = new HttpClient();
    int code = client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    method.releaseConnection();
    if (code >= 400) {
        System.out.println("Error occurred during transformation  submission.");
        return null;
    }
    return response;
}

From source file:org.silverpeas.openoffice.windows.webdav.WebdavManager.java

/**
 * Update a ressource on the webdav file server.
 *
 * @param uri the uri to the ressource.//from   w  w w. j  ava 2s.  co  m
 * @param localFilePath the path to the file to be uploaded on the filesystem.
 * @param lockToken the current lock token.
 * @throws IOException
 */
public void putFile(URI uri, String localFilePath, String lockToken) throws IOException {
    String url = decodeURI(uri);
    // Checks if file still exists
    if (!isFileExist(url)) {
        logger.log(Level.SEVERE, MessageUtil.getMessage("error.remote.file"));
        throw new IOException(MessageUtil.getMessage("error.remote.file"));
    }
    PutMethod putMethod = new PutMethod(url);
    logger.log(Level.INFO, "{0} {1}",
            new Object[] { MessageUtil.getMessage("info.webdav.put"), localFilePath });
    File localFile = new File(localFilePath);
    String remoteFileName = uri.getPath().substring(uri.getPath().lastIndexOf('/') + 1);
    UploadProgressBar progress = new UploadProgressBar();
    progress.setMaximum(new Long(localFile.length()).intValue());
    progress.setMessage(MessageUtil.getMessage("uploading.remote.file") + ' ' + remoteFileName);
    MonitoredInputStream is = new MonitoredInputStream(new BufferedInputStream(new FileInputStream(localFile)));
    is.addPropertyChangeListener(progress);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] data = new byte[64];
    int c;
    while ((c = is.read(data)) > -1) {
        baos.write(data, 0, c);
    }
    RequestEntity requestEntity = new ByteArrayRequestEntity(baos.toByteArray());
    putMethod.setRequestEntity(requestEntity);
    putMethod.setRequestHeader(PutMethod.HEADER_LOCK_TOKEN, lockToken);
    client.executeMethod(putMethod);
    progress.close();
    if (putMethod.succeeded()) {
        logger.log(Level.INFO, MessageUtil.getMessage("info.file.updated"));
    } else {
        throw new IOException(MessageUtil.getMessage("error.put.remote.file") + " - "
                + putMethod.getStatusCode() + " - " + putMethod.getStatusText());
    }
}

From source file:org.springbyexample.httpclient.HttpClientOxmTemplate.java

/**
 * Execute post method./*from  w w w  . jav  a2  s. c o  m*/
 * 
 * @param   uri             URI to use when processing this HTTP request instead 
 *                          of using the default URI.
 * @param   requestPayload  Request data to post after marshalling.  
 *                          The <code>Marshaller</code> should be able to 
 *                          process this instance. 
 * @param   hParams         Parameters for the HTTP post.
 * @param   callback        Callback with HTTP method's response.
 */
public void executePostMethod(String uri, T requestPayload, Map<String, String> hParams,
        ResponseCallback<?> callback) {
    PostMethod post = new PostMethod(uri);

    if (requestPayload != null) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            marshaller.marshal(requestPayload, new StreamResult(out));
        } catch (IOException e) {
            throw new MarshallingFailureException(e.getMessage(), e);
        }

        post.setRequestEntity(new ByteArrayRequestEntity(out.toByteArray()));
    }

    processHttpMethodParams(post, hParams);

    processHttpMethod(post, callback);
}

From source file:org.springbyexample.httpclient.HttpClientTemplate.java

/**
 * Execute post method.//from   w  ww. j a  v  a  2s .  co  m
 * 
 * @param   input           Byte array <code>RequestEntity</code> to post 
 *                          for the request's data.
 * @param   callback        Callback with HTTP method's response.
 */
public void executePostMethod(byte[] input, ResponseCallback<?> callback) {
    executePostMethod(defaultUri, (input != null ? new ByteArrayRequestEntity(input) : null), null, callback);
}

From source file:org.springframework.ws.transport.http.CommonsHttpConnection.java

@Override
protected void onSendAfterWrite(WebServiceMessage message) throws IOException {
    postMethod.setRequestEntity(new ByteArrayRequestEntity(requestBuffer.toByteArray()));
    requestBuffer = null;/*from ww  w .  j  a v a 2  s .  c  om*/
    try {
        httpClient.executeMethod(postMethod);
    } catch (IllegalStateException ex) {
        if ("Connection factory has been shutdown.".equals(ex.getMessage())) {
            // The application context has been closed, resulting in a connection factory shutdown and an ISE.
            // Let's create a new connection factory for this connection only.
            connectionManager = new MultiThreadedHttpConnectionManager();
            httpClient.setHttpConnectionManager(connectionManager);
            httpClient.executeMethod(postMethod);
        } else {
            throw ex;
        }
    }
}

From source file:org.waveprotocol.box.waveimport.google.RobotApi.java

private JSONObject callRobotApi(String method, Map<String, Object> params) throws IOException {
    JSONArray ops = new JSONArray();
    try {/*from   w ww.j  av a  2  s .c o  m*/
        JSONObject jsonParams = new JSONObject();
        for (Map.Entry<String, Object> e : params.entrySet()) {
            jsonParams.put(e.getKey(), e.getValue());
        }
        JSONObject op = new JSONObject();
        op.put("params", jsonParams);
        op.put("method", method);
        op.put("id", OP_ID);
        ops.put(op);
    } catch (JSONException e) {
        throw new RuntimeException("Failed to construct JSON object", e);
    }
    PostMethod req = new PostMethod(baseUrl);
    log.info("payload=" + ops);
    req.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
    req.setRequestEntity(new ByteArrayRequestEntity(ops.toString().getBytes(Charsets.UTF_8)));
    System.out.println("req: " + ops.toString());
    fetch.fetch(req, robotErrorCode401Detector);
    JSONObject result = parseJsonResponseBody(req.getResponseHeaders(), req.getResponseBody());
    log.info("result=" + ValueUtils.abbrev("" + result, 500));
    try {
        if (result.has("error")) {
            log.warning("Error result: " + result);
            JSONObject error = result.getJSONObject("error");
            throw new RuntimeException("Error from robot API: " + error);
        } else if (result.has("data")) {
            JSONObject data = result.getJSONObject("data");
            if (data.length() == 0) {
                // Apparently, the server often sends {"id":"op_id", "data":{}} when
                // something went wrong on the server side, so we translate that to an
                // IOException.
                throw new IOException("Robot API response looks like an error: " + result);
            } else {
                return data;
            }
        } else {
            throw new RuntimeException("Result has neither error nor data: " + result);
        }
    } catch (JSONException e) {
        throw new RuntimeException("JSONException parsing result: " + result, e);
    }
}

From source file:org.waveprotocol.box.waveimport.google.RobotApi.java

private JSONObject callRobotApi1(String method, Map<String, Object> params) throws IOException {
    JSONArray ops = new JSONArray();
    try {/*ww w.  j a  va 2 s . c o  m*/
        JSONObject jsonParams = new JSONObject();
        for (Map.Entry<String, Object> e : params.entrySet()) {
            jsonParams.put(e.getKey(), e.getValue());
        }
        JSONObject op = new JSONObject();
        op.put("params", jsonParams);
        op.put("method", method);
        op.put("id", OP_ID);
        ops.put(op);
    } catch (JSONException e) {
        throw new RuntimeException("Failed to construct JSON object", e);
    }
    PostMethod req = new PostMethod(baseUrl);
    log.info("payload=" + ops);
    req.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
    req.setRequestEntity(new ByteArrayRequestEntity(ops.toString().getBytes(Charsets.UTF_8)));
    System.out.println("req: " + ops.toString());
    fetch.fetch(req, robotErrorCode401Detector);
    JSONObject result = parseJsonResponseBody(req.getRequestHeaders(), req.getResponseBody());
    log.info("result=" + ValueUtils.abbrev("" + result, 500));
    return result;
}

From source file:org.waveprotocol.box.waveimport.WaveImport.java

private String importRequest(String url, WaveId waveId, WaveletId waveletId, String json) throws IOException {
    HttpClient httpClient = new HttpClient();
    PostMethod request = new PostMethod(url);
    request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
    request.setRequestHeader("domain", waveServerDomain);
    request.setRequestHeader("waveId", waveId.serialise());
    request.setRequestHeader("waveletId", waveletId.serialise());
    request.setRequestEntity(new ByteArrayRequestEntity(json.getBytes("utf8")));
    if (httpClient.executeMethod(request) != 200) {
        throw new IOException(request.getResponseBodyAsString());
    }/* w  w w  . j  a v a2  s. c o m*/
    return request.getResponseBodyAsString();
}

From source file:org.wso2.carbon.appfactory.git.repository.provider.SCMManagerBasedGITRepositoryProvider.java

/**
 * {@inheritDoc}/*  www.  ja  v  a 2  s  .c  om*/
 */
@Override
public String createRepository(String applicationKey, String tenantDomain) throws RepositoryMgtException {

    HttpClient client = getClient();
    PostMethod post = new PostMethod(getServerURL() + REST_BASE_URI + REST_CREATE_REPOSITORY_URI);
    Repository repository = new Repository();
    repository.setName(applicationKey);
    repository.setType("git");

    Permission permission = new Permission();
    permission.setGroupPermission(true);
    permission.setName(applicationKey);
    permission.setType(PermissionType.WRITE);
    ArrayList<Permission> permissions = new ArrayList<Permission>();
    permissions.add(permission);

    repository.setPermissions(permissions);

    post.setRequestEntity(new ByteArrayRequestEntity(getRepositoryAsString(repository)));
    post.setDoAuthentication(true);
    post.addRequestHeader("Content-Type", "application/xml;charset=UTF-8");

    String url;
    try {
        client.executeMethod(post);
    } catch (IOException e) {
        String msg = "Error while invoking the web service";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    } finally {
        post.releaseConnection();
    }
    if (post.getStatusCode() == HttpStatus.SC_CREATED) {
        url = getAppRepositoryURL(applicationKey, tenantDomain);
    } else {
        String msg = "Repository creation is failed for " + applicationKey + " server returned status "
                + post.getStatusText();
        log.error(msg);
        throw new RepositoryMgtException(msg);
    }

    return url;
}