Search in sources :

Example 76 with PutMethod

use of org.apache.commons.httpclient.methods.PutMethod in project xwiki-platform by xwiki.

the class InstallMojo method executePutXml.

private PutMethod executePutXml(String uri, Object object, Marshaller marshaller, HttpClient httpClient) throws Exception {
    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", MediaType.APPLICATION_XML.toString());
    StringWriter writer = new StringWriter();
    marshaller.marshal(object, writer);
    RequestEntity entity = new StringRequestEntity(writer.toString(), MediaType.APPLICATION_XML.toString(), "UTF-8");
    putMethod.setRequestEntity(entity);
    httpClient.executeMethod(putMethod);
    return putMethod;
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) StringWriter(java.io.StringWriter) PutMethod(org.apache.commons.httpclient.methods.PutMethod) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity)

Example 77 with PutMethod

use of org.apache.commons.httpclient.methods.PutMethod in project xwiki-platform by xwiki.

the class InstallMojo method installExtensions.

private void installExtensions(Marshaller marshaller, Unmarshaller unmarshaller, HttpClient httpClient) throws Exception {
    InstallRequest installRequest = new InstallRequest();
    // Set a job id to save the job result
    installRequest.setId("extension", "provision", UUID.randomUUID().toString());
    installRequest.setInteractive(false);
    // Set the extension list to install
    for (ExtensionId extensionId : this.extensionIds) {
        org.xwiki.extension.ExtensionId extId = new org.xwiki.extension.ExtensionId(extensionId.getId(), extensionId.getVersion());
        getLog().info(String.format("Installing extension [%s]...", extId));
        installRequest.addExtension(extId);
    }
    // Set the namespaces into which to install the extensions
    if (this.namespaces == null || this.namespaces.isEmpty()) {
        installRequest.addNamespace("wiki:xwiki");
    } else {
        for (String namespace : this.namespaces) {
            installRequest.addNamespace(namespace);
        }
    }
    // Set any user for installing pages (if defined)
    if (this.installUserReference != null) {
        installRequest.setProperty("user.reference", new DocumentReference("xwiki", "XWiki", "superadmin"));
    }
    JobRequest request = getModelFactory().toRestJobRequest(installRequest);
    String uri = String.format("%s/jobs?jobType=install&async=false", this.xwikiRESTURL);
    PutMethod putMethod = executePutXml(uri, request, marshaller, httpClient);
    // Verify results
    // Verify that we got a 200 response
    int statusCode = putMethod.getStatusCode();
    if (statusCode < 200 || statusCode >= 300) {
        throw new MojoExecutionException(String.format("Job execution failed. Response status code [%s], reason [%s]", statusCode, putMethod.getResponseBodyAsString()));
    }
    // Get the job status
    JobStatus jobStatus = (JobStatus) unmarshaller.unmarshal(putMethod.getResponseBodyAsStream());
    if (jobStatus.getErrorMessage() != null && jobStatus.getErrorMessage().length() > 0) {
        throw new MojoExecutionException(String.format("Job execution failed. Reason [%s]", jobStatus.getErrorMessage()));
    }
    // Release connection
    putMethod.releaseConnection();
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) InstallRequest(org.xwiki.extension.job.InstallRequest) ExtensionId(org.xwiki.extension.repository.xwiki.model.jaxb.ExtensionId) JobStatus(org.xwiki.rest.model.jaxb.JobStatus) JobRequest(org.xwiki.rest.model.jaxb.JobRequest) PutMethod(org.apache.commons.httpclient.methods.PutMethod) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 78 with PutMethod

use of org.apache.commons.httpclient.methods.PutMethod in project fabric8 by jboss-fuse.

the class CrmSecureTest method putCustomerTest.

/**
 * HTTP PUT http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the update_customer.xml file to update the customer information for customer 123.
 * <p/>
 * On the server side, it matches the CustomerService's updateCustomer() method
 *
 * @throws Exception
 */
@Test
public void putCustomerTest() throws IOException {
    LOG.info("============================================");
    LOG.info("Sent HTTP PUT request to update customer info");
    String inputFile = this.getClass().getResource("/update_customer.xml").getFile();
    File input = new File(inputFile);
    PutMethod put = new PutMethod(CUSTOMER_SERVICE_URL);
    put.getHostAuthState().setAuthScheme(scheme);
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    put.setRequestEntity(entity);
    int result = 0;
    try {
        result = httpClient.executeMethod(put);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        LOG.info(put.getResponseBodyAsString());
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error("You should build the 'rest' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'rest' quick start root");
        fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        put.releaseConnection();
    }
    assertEquals(result, 200);
}
Also used : FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) PutMethod(org.apache.commons.httpclient.methods.PutMethod) IOException(java.io.IOException) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) File(java.io.File) Test(org.junit.Test)

Example 79 with PutMethod

use of org.apache.commons.httpclient.methods.PutMethod in project jaggery by wso2.

the class XMLHttpRequestHostObject method send.

private void send(Context cx, Object obj) throws ScriptException {
    final HttpMethodBase method;
    if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod(this.url);
    } else if ("HEAD".equalsIgnoreCase(methodName)) {
        method = new HeadMethod(this.url);
    } else if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod post = new PostMethod(this.url);
        if (obj instanceof FormDataHostObject) {
            FormDataHostObject fd = ((FormDataHostObject) obj);
            List<Part> parts = new ArrayList<Part>();
            for (Map.Entry<String, String> entry : fd) {
                parts.add(new StringPart(entry.getKey(), entry.getValue()));
            }
            post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));
        } else {
            String content = getRequestContent(obj);
            if (content != null) {
                post.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
            }
        }
        method = post;
    } else if ("PUT".equalsIgnoreCase(methodName)) {
        PutMethod put = new PutMethod(this.url);
        String content = getRequestContent(obj);
        if (content != null) {
            put.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(content.getBytes())));
        }
        method = put;
    } else if ("DELETE".equalsIgnoreCase(methodName)) {
        method = new DeleteMethod(this.url);
    } else if ("TRACE".equalsIgnoreCase(methodName)) {
        method = new TraceMethod(this.url);
    } else if ("OPTIONS".equalsIgnoreCase(methodName)) {
        method = new OptionsMethod(this.url);
    } else {
        throw new ScriptException("Unknown HTTP method : " + methodName);
    }
    for (Header header : requestHeaders) {
        method.addRequestHeader(header);
    }
    if (username != null) {
        httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    }
    this.method = method;
    final XMLHttpRequestHostObject xhr = this;
    if (async) {
        updateReadyState(cx, xhr, LOADING);
        final ContextFactory factory = cx.getFactory();
        final ExecutorService es = Executors.newSingleThreadExecutor();
        es.submit(new Callable() {

            public Object call() throws Exception {
                Context ctx = RhinoEngine.enterContext(factory);
                try {
                    executeRequest(ctx, xhr);
                } catch (ScriptException e) {
                    log.error(e.getMessage(), e);
                } finally {
                    es.shutdown();
                    RhinoEngine.exitContext();
                }
                return null;
            }
        });
    } else {
        executeRequest(cx, xhr);
    }
}
Also used : InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) ArrayList(java.util.ArrayList) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) Callable(java.util.concurrent.Callable) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) HeadMethod(org.apache.commons.httpclient.methods.HeadMethod) OptionsMethod(org.apache.commons.httpclient.methods.OptionsMethod) Context(org.mozilla.javascript.Context) DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) HttpMethodBase(org.apache.commons.httpclient.HttpMethodBase) TraceMethod(org.apache.commons.httpclient.methods.TraceMethod) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) IOException(java.io.IOException) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) ContextFactory(org.mozilla.javascript.ContextFactory) Header(org.apache.commons.httpclient.Header) ByteArrayInputStream(java.io.ByteArrayInputStream) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) Part(org.apache.commons.httpclient.methods.multipart.Part) GetMethod(org.apache.commons.httpclient.methods.GetMethod) ExecutorService(java.util.concurrent.ExecutorService) PutMethod(org.apache.commons.httpclient.methods.PutMethod) ScriptableObject(org.mozilla.javascript.ScriptableObject) Map(java.util.Map)

Example 80 with PutMethod

use of org.apache.commons.httpclient.methods.PutMethod in project application by collectionspace.

the class ServicesConnection method createMethod.

private HttpMethod createMethod(RequestMethod method, String uri, InputStream data) throws ConnectionException {
    uri = prepend_base(uri);
    if (uri == null)
        throw new ConnectionException("URI must not be null");
    // Extract QP's
    int qp_start = uri.indexOf('?');
    String qps = null;
    if (qp_start != -1) {
        qps = uri.substring(qp_start + 1);
        uri = uri.substring(0, qp_start);
    }
    HttpMethod out = null;
    switch(method) {
        case POST:
            {
                out = new PostMethod(uri);
                if (data != null)
                    ((PostMethod) out).setRequestEntity(new InputStreamRequestEntity(data));
                break;
            }
        case PUT:
            {
                out = new PutMethod(uri);
                if (data != null)
                    ((PutMethod) out).setRequestEntity(new InputStreamRequestEntity(data));
                break;
            }
        case GET:
            out = new GetMethod(uri);
            break;
        case DELETE:
            out = new DeleteMethod(uri);
            break;
        default:
            throw new ConnectionException("Unsupported method " + method, 0, uri);
    }
    if (qps != null)
        out.setQueryString(qps);
    out.setDoAuthentication(true);
    return out;
}
Also used : InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) PostMethod(org.apache.commons.httpclient.methods.PostMethod) GetMethod(org.apache.commons.httpclient.methods.GetMethod) PutMethod(org.apache.commons.httpclient.methods.PutMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Aggregations

PutMethod (org.apache.commons.httpclient.methods.PutMethod)94 Test (org.junit.Test)49 GetMethod (org.apache.commons.httpclient.methods.GetMethod)29 AbstractHttpTest (org.xwiki.test.rest.framework.AbstractHttpTest)21 StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)19 Page (org.xwiki.rest.model.jaxb.Page)15 HttpClient (org.apache.commons.httpclient.HttpClient)14 IOException (java.io.IOException)13 RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)13 DeleteMethod (org.apache.commons.httpclient.methods.DeleteMethod)12 PostMethod (org.apache.commons.httpclient.methods.PostMethod)10 InputStreamRequestEntity (org.apache.commons.httpclient.methods.InputStreamRequestEntity)7 DeleteMethod (org.apache.jackrabbit.webdav.client.methods.DeleteMethod)7 Link (org.xwiki.rest.model.jaxb.Link)7 Header (org.apache.commons.httpclient.Header)6 HttpMethod (org.apache.commons.httpclient.HttpMethod)6 FileRequestEntity (org.apache.commons.httpclient.methods.FileRequestEntity)6 File (java.io.File)5 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)5 Object (org.xwiki.rest.model.jaxb.Object)5