Example usage for org.apache.commons.httpclient.methods PutMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PutMethod setRequestEntity

Introduction

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

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:de.mpg.escidoc.pubman.sword.SwordUtil.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * @param InputStream to upload//  ww w  .ja  va  2 s.  c o  m
 * @param mimetype The mimetype of the file
 * @param userHandle The userhandle to use for upload
 * @return The URL of the uploaded file.
 * @throws Exception If anything goes wrong...
 */
protected URL uploadFile(InputStream in, String mimetype, String userHandle, ZipEntry zipEntry)
        throws Exception {
    // Prepare the HttpMethod.
    String fwUrl = de.mpg.escidoc.services.framework.ServiceLocator.getFrameworkUrl();
    PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
    method.setRequestEntity(new InputStreamRequestEntity(in, -1));
    method.setRequestHeader("Content-Type", mimetype);
    method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
    // Execute the method with HttpClient.
    HttpClient client = new HttpClient();
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    InitialContext context = new InitialContext();
    XmlTransformingBean ctransforming = new XmlTransformingBean();
    return ctransforming.transformUploadResponseToFileURL(response);
}

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

@Override
public void notifyRecommendations(String modelSetId, String simulationid, String userId, Recommendations rec)
        throws LpRestException {
    String contentType = "application/xml";

    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/bridge/notify/%s", DefaultRestResource.REST_URI, modelSetId);

    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", contentType);

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("simulationid", simulationid);
    queryString[1] = new NameValuePair("userid", userId);
    putMethod.setQueryString(queryString);

    try {// w w  w . j a va  2 s  .co  m
        JAXBContext jc = JAXBContext.newInstance(Recommendations.class);
        Writer recWriter = new StringWriter();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(rec, recWriter);

        RequestEntity requestEntity = new StringRequestEntity(recWriter.toString(), contentType, "UTF-8");
        putMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(putMethod);
    } catch (JAXBException | IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:edu.indiana.d2i.htrc.portal.HTRCAgentClient.java

public JobDetailsBean submitJob(JobSubmitBean jobSubmitBean) {
    PutMethod putMethod = null;
    JobDetailsBean jobSubmitResponse = null;
    try {/*from  w  w  w. ja  v a 2s . c o m*/
        String submitJobUrl = PlayConfWrapper.agentEndpoint() + PlayConfWrapper.jobSubmitURL() + "/"
                + jobSubmitBean.getAlgorithmName();
        putMethod = new PutMethod(submitJobUrl);

        StringRequestEntity requestEntity = new StringRequestEntity(jobSubmitBean.toXML());
        if (log.isDebugEnabled()) {
            log.debug("submitURL " + submitJobUrl);
            log.debug("request body " + jobSubmitBean.toXML());
        }
        putMethod.setRequestEntity(requestEntity);
        putMethod.setRequestHeader("Authorization", "Bearer " + accessToken);
        putMethod.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");

        int responsecode = client.executeMethod(putMethod);
        this.responseCode = responsecode;
        if (responsecode == 200) {
            jobSubmitResponse = parseJobSubmit(putMethod.getResponseBodyAsStream());
            log.debug(putMethod.getResponseBodyAsString());
        } else if (responsecode == 401 && (renew < MAX_RENEW)) {
            try {
                accessToken = HTRCPersistenceAPIClient.renewToken(refreshToken);
                renew++;
                return submitJob(jobSubmitBean);
            } catch (Exception e) {
                throw new IOException(e);
            }
        } else {
            renew = 0;
            log.error(String.format("Unable to submit job %s to agent. Response code %d",
                    jobSubmitBean.getJobName(), responsecode));
            jobSubmitResponse = null;
        }
    } catch (IOException | XMLStreamException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    return jobSubmitResponse;

}

From source file:ch.cyberduck.core.dav.DAVResource.java

/**
 * Execute the PUT method for the given path.
 *
 * @param path          the server relative path to put the data
 * @param requestEntity The input stream.
 * @return true if the method is succeeded.
 * @throws IOException/*from w w w . j a v  a  2s  .c o m*/
 */
public boolean putMethod(String path, RequestEntity requestEntity) throws IOException {

    setClient();

    PutMethod method = new PutMethod(URIUtil.encodePathQuery(path)) {
        @Override
        public boolean getFollowRedirects() {
            // See #3206. Redirects for uploads are not allowed without user interaction by default.
            return true;
        }
    };

    // Activates 'Expect: 100-Continue' handshake. The purpose of
    // the 'Expect: 100-Continue' handshake to allow a client that is
    // sending a request message with a request body to determine if
    // the origin server is willing to accept the request (based on
    // the request headers) before the client sends the request body.
    //
    // Otherwise, upload will fail when using digest authentication.
    // Fix #2268
    method.setUseExpectHeader(true);

    generateIfHeader(method);
    method.setRequestEntity(requestEntity);

    generateTransactionHeader(method);
    generateAdditionalHeaders(method);
    int statusCode = client.executeMethod(method);

    method.releaseConnection();

    setStatusCode(statusCode, method.getStatusText());
    return isHttpSuccess(statusCode);
}

From source file:de.mpg.mpdl.inge.pubman.web.multipleimport.ImportProcess.java

private String createTaskItemXml() {
    try {//  w  ww. ja  v a  2s .  co  m

        String fwUrl = PropertyReader.getFrameworkUrl();
        HttpClient client = new HttpClient();
        ProxyHelper.setProxy(client, fwUrl);

        StringBuilder sb = new StringBuilder(ResourceUtil.getResourceAsString(
                "multipleImport/ImportTaskTemplate.xml", ImportProcess.class.getClassLoader()));
        replace("$01", escape(this.escidocContext.getObjectId()), sb);
        replace("$02", escape(PropertyReader.getProperty("escidoc.import.task.content-model")), sb);
        replace("$03", escape("Import Task Item for import " + name + " "), sb);

        // Upload original data
        PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
        method.setRequestHeader("Content-Type", this.format.toString());
        method.setRequestHeader("Cookie", "escidocCookie=" + this.user.getHandle());
        InputStream is = new FileInputStream(this.formatProcessor.getSourceFile());
        method.setRequestEntity(new InputStreamRequestEntity(is));
        client.executeMethod(method);
        is.close();
        String response = method.getResponseBodyAsString();
        URL originalDataUrl = xmlTransforming.transformUploadResponseToFileURL(response);

        replace("$04", escape(this.name), sb);
        replace("$05", escape(this.fileName), sb);
        replace("$06", escape(originalDataUrl.toExternalForm()), sb);
        replace("$07", escape(log.getStoredId() + ""), sb);
        replace("$08", escape(this.format.toString()), sb);
        replace("$09", escape(String.valueOf(this.formatProcessor.getLength())), sb);

        // Upload and create task item xml
        File tempLogXml = File.createTempFile("multipleImportLogXml", "xml");
        Writer fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempLogXml), "UTF-8"));
        log.toXML(fw);
        fw.flush();
        fw.close();

        PutMethod method2 = new PutMethod(fwUrl + "/st/staging-file");
        method2.setRequestHeader("Content-Type", "text/xml");
        method2.setRequestHeader("Cookie", "escidocCookie=" + this.user.getHandle());
        is = new FileInputStream(tempLogXml);
        method2.setRequestEntity(new InputStreamRequestEntity(is));
        client.executeMethod(method2);
        is.close();

        response = method2.getResponseBodyAsString();
        URL logXmlUrl = xmlTransforming.transformUploadResponseToFileURL(response);

        replace("$10", escape(this.name), sb);
        replace("$11", "importlog.xml", sb);
        replace("$12", escape(logXmlUrl.toExternalForm()), sb);
        replace("$13", escape(log.getStoredId() + ""), sb);
        replace("$14", escape(String.valueOf(tempLogXml.length())), sb);

        tempLogXml.delete();

        /*
         * String taskItemXml =
         * ResourceUtil.getResourceAsString("multipleImport/ImportTaskTemplate.xml"); taskItemXml =
         * taskItemXml.replace("$1", escape(this.escidocContext.getObjectId())); taskItemXml =
         * taskItemXml.replace("$2",
         * escape(PropertyReader.getProperty("escidoc.import.task.content-model"))); taskItemXml =
         * taskItemXml.replace("$4", escape(this.name)); taskItemXml = taskItemXml.replace("$5",
         * escape(this.fileName)); taskItemXml = taskItemXml.replace("$6",
         * escape(this.formatProcessor.getDataAsBase64())); taskItemXml = taskItemXml.replace("$7",
         * escape(log.getStoredId() + "")); taskItemXml = taskItemXml.replace("$8",
         * escape(this.format.toString())); taskItemXml = taskItemXml.replace("$9",
         * escape(this.formatProcessor.getLength() + ""));
         */
        log.finishItem();

        log.close();

        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.mpg.escidoc.pubman.multipleimport.ImportProcess.java

private String createTaskItemXml() {
    try {/*from   ww w .  j  a v a 2s  . com*/

        String fwUrl = de.mpg.escidoc.services.framework.ServiceLocator.getFrameworkUrl();
        HttpClient client = new HttpClient();
        ProxyHelper.setProxy(client, fwUrl);

        StringBuilder sb = new StringBuilder(ResourceUtil.getResourceAsString(
                "multipleImport/ImportTaskTemplate.xml", ImportProcess.class.getClassLoader()));
        replace("$01", escape(this.escidocContext.getObjectId()), sb);
        replace("$02", escape(PropertyReader.getProperty("escidoc.import.task.content-model")), sb);
        replace("$03", escape("Import Task Item for import " + name + " "), sb);

        //Upload original data
        PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
        method.setRequestHeader("Content-Type", this.format.toString());
        method.setRequestHeader("Cookie", "escidocCookie=" + this.user.getHandle());
        InputStream is = new FileInputStream(this.formatProcessor.getSourceFile());
        method.setRequestEntity(new InputStreamRequestEntity(is));
        client.executeMethod(method);
        is.close();
        String response = method.getResponseBodyAsString();
        URL originalDataUrl = xmlTransforming.transformUploadResponseToFileURL(response);

        replace("$04", escape(this.name), sb);
        replace("$05", escape(this.fileName), sb);
        replace("$06", escape(originalDataUrl.toExternalForm()), sb);
        replace("$07", escape(log.getStoredId() + ""), sb);
        replace("$08", escape(this.format.toString()), sb);
        replace("$09", escape(String.valueOf(this.formatProcessor.getLength())), sb);

        //Upload and create task item xml
        File tempLogXml = File.createTempFile("multipleImportLogXml", "xml");
        Writer fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempLogXml), "UTF-8"));
        log.toXML(fw);
        fw.flush();
        fw.close();

        PutMethod method2 = new PutMethod(fwUrl + "/st/staging-file");
        method2.setRequestHeader("Content-Type", "text/xml");
        method2.setRequestHeader("Cookie", "escidocCookie=" + this.user.getHandle());
        is = new FileInputStream(tempLogXml);
        method2.setRequestEntity(new InputStreamRequestEntity(is));
        client.executeMethod(method2);
        is.close();

        response = method2.getResponseBodyAsString();
        URL logXmlUrl = xmlTransforming.transformUploadResponseToFileURL(response);

        replace("$10", escape(this.name), sb);
        replace("$11", "importlog.xml", sb);
        replace("$12", escape(logXmlUrl.toExternalForm()), sb);
        replace("$13", escape(log.getStoredId() + ""), sb);
        replace("$14", escape(String.valueOf(tempLogXml.length())), sb);

        tempLogXml.delete();

        /*
         String taskItemXml = ResourceUtil.getResourceAsString("multipleImport/ImportTaskTemplate.xml");
         taskItemXml = taskItemXml.replace("$1", escape(this.escidocContext.getObjectId()));
         taskItemXml = taskItemXml.replace("$2",
            escape(PropertyReader.getProperty("escidoc.import.task.content-model")));
         taskItemXml = taskItemXml.replace("$4", escape(this.name));
         taskItemXml = taskItemXml.replace("$5", escape(this.fileName));
         taskItemXml = taskItemXml.replace("$6", escape(this.formatProcessor.getDataAsBase64()));
         taskItemXml = taskItemXml.replace("$7", escape(log.getStoredId() + ""));
         taskItemXml = taskItemXml.replace("$8", escape(this.format.toString()));
         taskItemXml = taskItemXml.replace("$9", escape(this.formatProcessor.getLength() + ""));
        */
        log.finishItem();

        log.close();

        return sb.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java

public String updateClientAppStatus(String clientId, Integer status) {
    PutMethod put = new PutMethod(baseOAuth20Uri + APPLICATION_ENDPOINT + "/" + clientId);
    String response = null;/*from www  . java 2 s . co  m*/
    try {
        //put.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(clientId));
        JSONObject json = new JSONObject();
        json.put("status", status);
        String requestBody = json.toString();
        RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8");
        put.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        put.setRequestEntity(requestEntity);
        response = readResponse(put);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot update client app", e);
    } catch (JSONException e) {
        log.error("cannot update client app", e);
    }
    return response;
}

From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java

public String updateScope(String scope, String description, Integer ccExpiresIn, Integer passExpiresIn) {
    PutMethod put = new PutMethod(baseOAuth20Uri + SCOPE_ENDPOINT + "/" + scope);
    String response = null;/*from w w  w .j  ava  2 s .  com*/
    try {
        JSONObject json = new JSONObject();
        json.put("description", description);
        json.put("cc_expires_in", ccExpiresIn);
        json.put("pass_expires_in", passExpiresIn);
        String requestBody = json.toString();
        RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8");
        put.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        put.setRequestEntity(requestEntity);
        response = readResponse(put);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot update scope", e);
    } catch (JSONException e) {
        log.error("cannot update scope", e);
    }
    return response;
}

From source file:edu.unc.lib.dl.admin.controller.AbstractSwordController.java

public String updateDatastream(String pid, String datastream, HttpServletRequest request,
        HttpServletResponse response) {/*from w  ww  .  j  ava2 s . c om*/
    String responseString = null;
    String dataUrl = swordUrl + "object/" + pid;
    if (datastream != null)
        dataUrl += "/" + datastream;

    Abdera abdera = new Abdera();
    Entry entry = abdera.newEntry();
    Parser parser = abdera.getParser();
    Document<FOMExtensibleElement> doc;
    HttpClient client;
    PutMethod method;

    ParserOptions parserOptions = parser.getDefaultParserOptions();
    parserOptions.setCharset(request.getCharacterEncoding());

    try {

        doc = parser.parse(request.getInputStream(), parserOptions);
        entry.addExtension(doc.getRoot());

        client = HttpClientUtil.getAuthenticatedClient(dataUrl, swordUsername, swordPassword);
        client.getParams().setAuthenticationPreemptive(true);
        method = new PutMethod(dataUrl);
        // Pass the users groups along with the request
        method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());

        Header header = new Header("Content-Type", "application/atom+xml");
        method.setRequestHeader(header);
        StringWriter stringWriter = new StringWriter(2048);
        StringRequestEntity requestEntity;
        entry.writeTo(stringWriter);
        requestEntity = new StringRequestEntity(stringWriter.toString(), "application/atom+xml", "UTF-8");
        method.setRequestEntity(requestEntity);
    } catch (UnsupportedEncodingException e) {
        log.error("Encoding not supported", e);
        return null;
    } catch (IOException e) {
        log.error("IOException while writing entry", e);
        return null;
    }

    try {
        client.executeMethod(method);
        response.setStatus(method.getStatusCode());
        if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            // success
            return "";
        } else if (method.getStatusCode() >= 400 && method.getStatusCode() <= 500) {
            if (method.getStatusCode() == 500)
                log.warn("Failed to upload " + datastream + " " + method.getURI().getURI());
            // probably a validation problem
            responseString = method.getResponseBodyAsString();
            return responseString;
        } else {
            response.setStatus(500);
            throw new Exception("Failure to update fedora content due to response of: "
                    + method.getStatusLine().toString() + "\nPath was: " + method.getURI().getURI());
        }
    } catch (Exception e) {
        log.error("Error while attempting to stream Fedora content for " + pid, e);
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return responseString;
}

From source file:com.wandisco.s3hdfs.rewrite.redirect.MetadataFileRedirect.java

/**
 * Sends a PUT command to create an empty file inside of HDFS.
 * It uses the URL from the original request to do so.
 * It will then consume the 307 response and write to the DataNode as well.
 * The data is "small" in hopes that this will be relatively quick.
 *
 * @throws IOException//from  w w  w  .  jav a 2s  .  c om
 * @throws ServletException
 */
public void sendCreate(String nnHostAddress, String userName) throws IOException, ServletException {
    // Set up HttpPut
    String[] nnHost = nnHostAddress.split(":");
    String metapath = replaceUri(request.getRequestURI(), OBJECT_FILE_NAME, META_FILE_NAME);

    PutMethod httpPut = (PutMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]),
            "CREATE&overwrite=true", userName, metapath, PUT);
    Enumeration headers = request.getHeaderNames();
    Properties metadata = new Properties();

    // Set custom metadata headers
    while (headers.hasMoreElements()) {
        String key = (String) headers.nextElement();
        if (key.startsWith("x-amz-meta-")) {
            String value = request.getHeader(key);
            metadata.setProperty(key, value);
        }
    }
    // Include lastModified header
    SimpleDateFormat rc228 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    String modTime = rc228.format(Calendar.getInstance().getTime());
    metadata.setProperty("Last-Modified", modTime);

    // Store metadata headers into serialized HashMap in HttpPut entity.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    metadata.store(baos, null);

    httpPut.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
    httpPut.setRequestHeader(S3_HEADER_NAME, S3_HEADER_VALUE);

    httpClient.executeMethod(httpPut);
    LOG.debug("1st response: " + httpPut.getStatusLine().toString());

    boolean containsRedirect = (httpPut.getResponseHeader("Location") != null);

    if (!containsRedirect) {
        httpPut.releaseConnection();
        LOG.error("1st response did not contain redirect. " + "No metadata will be created.");
        return;
    }

    // Handle redirect header transition
    assert httpPut.getStatusCode() == 307;
    Header locationHeader = httpPut.getResponseHeader("Location");
    httpPut.setURI(new URI(locationHeader.getValue(), true));

    // Consume response and re-allocate connection for redirect
    httpPut.releaseConnection();
    httpClient.executeMethod(httpPut);

    LOG.debug("2nd response: " + httpPut.getStatusLine().toString());

    if (httpPut.getStatusCode() != 200) {
        LOG.debug("Response not 200: " + httpPut.getResponseBodyAsString());
        return;
    }

    assert httpPut.getStatusCode() == 200;
}