Search in sources :

Example 21 with FilePart

use of org.apache.commons.httpclient.methods.multipart.FilePart in project zm-mailbox by Zimbra.

the class TestFileUpload method testAdminUploadWithCsrfInFormField.

@Test
public void testAdminUploadWithCsrfInFormField() throws Exception {
    SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
    com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
    req.setCsrfSupported(true);
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    String csrfToken = authResp.getCsrfToken();
    int port = 7071;
    try {
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    } catch (ServiceException e) {
        ZimbraLog.test.error("Unable to get admin SOAP port", e);
    }
    String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
    PostMethod post = new PostMethod(Url);
    FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes()));
    Part csrfPart = new StringPart("csrfToken", csrfToken);
    String contentType = "application/x-msdownload";
    part.setContentType(contentType);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpState state = new HttpState();
    state.addCookie(new org.apache.commons.httpclient.Cookie("localhost", ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false));
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setState(state);
    post.setRequestEntity(new MultipartRequestEntity(new Part[] { part, csrfPart }, post.getParams()));
    int statusCode = HttpClientUtil.executeMethod(client, post);
    Assert.assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode);
    String resp = post.getResponseBodyAsString();
    Assert.assertNotNull("Response should not be empty", resp);
    Assert.assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HeaderElement(org.apache.commons.httpclient.HeaderElement) Element(com.zimbra.common.soap.Element) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) HttpState(org.apache.commons.httpclient.HttpState) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) ServiceException(com.zimbra.common.service.ServiceException) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) SoapHttpTransport(com.zimbra.common.soap.SoapHttpTransport) Test(org.junit.Test)

Example 22 with FilePart

use of org.apache.commons.httpclient.methods.multipart.FilePart in project sling by apache.

the class SlingIntegrationTestClient method uploadToFileNodes.

/** Upload multiple files to file node structures */
public void uploadToFileNodes(String url, File[] localFiles, String[] fieldNames, String[] typeHints) throws IOException {
    List<Part> partsList = new ArrayList<Part>();
    for (int i = 0; i < localFiles.length; i++) {
        Part filePart = new FilePart(fieldNames[i], localFiles[i]);
        partsList.add(filePart);
        if (typeHints != null) {
            Part typeHintPart = new StringPart(fieldNames[i] + "@TypeHint", typeHints[i]);
            partsList.add(typeHintPart);
        }
    }
    final Part[] parts = partsList.toArray(new Part[partsList.size()]);
    final PostMethod post = new PostMethod(url);
    post.setFollowRedirects(false);
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    final int expected = 200;
    final int status = httpClient.executeMethod(post);
    if (status != expected) {
        throw new HttpStatusCodeException(expected, status, "POST", HttpTestBase.getResponseBodyAsStream(post, 0));
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) ArrayList(java.util.ArrayList) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart)

Example 23 with FilePart

use of org.apache.commons.httpclient.methods.multipart.FilePart in project sling by apache.

the class SlingIntegrationTestClient method createNode.

/** Create a node under given path, using a POST to Sling
     *  @param url under which node is created
     *  @param multiPart if true, does a multipart POST
     *  @param localFile file to upload
     *  @param fieldName name of the file field
     *  @param typeHint typeHint of the file field 
     *  @return the URL that Sling provides to display the node
     */
public String createNode(String url, NameValuePairList clientNodeProperties, Map<String, String> requestHeaders, boolean multiPart, File localFile, String fieldName, String typeHint) throws IOException {
    final PostMethod post = new PostMethod(url);
    post.setFollowRedirects(false);
    // create a private copy of the properties to not tamper with
    // the properties of the client
    NameValuePairList nodeProperties = new NameValuePairList(clientNodeProperties);
    // add sling specific properties
    nodeProperties.prependIfNew(":redirect", "*");
    nodeProperties.prependIfNew(":displayExtension", "");
    nodeProperties.prependIfNew(":status", "browser");
    // add fake property - otherwise the node is not created
    if (clientNodeProperties == null) {
        nodeProperties.add("jcr:created", "");
    }
    // force form encoding to UTF-8, which is what we use to convert the
    // string parts into stream data
    nodeProperties.addOrReplace("_charset_", "UTF-8");
    if (nodeProperties.size() > 0) {
        if (multiPart) {
            final List<Part> partList = new ArrayList<Part>();
            for (NameValuePair e : nodeProperties) {
                if (e.getValue() != null) {
                    partList.add(new StringPart(e.getName(), e.getValue(), "UTF-8"));
                }
            }
            if (localFile != null) {
                partList.add(new FilePart(fieldName, localFile));
                if (typeHint != null) {
                    partList.add(new StringPart(fieldName + "@TypeHint", typeHint));
                }
            }
            final Part[] parts = partList.toArray(new Part[partList.size()]);
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        } else {
            post.getParams().setContentCharset("UTF-8");
            for (NameValuePair e : nodeProperties) {
                post.addParameter(e.getName(), e.getValue());
            }
        }
    }
    if (requestHeaders != null) {
        for (Map.Entry<String, String> e : requestHeaders.entrySet()) {
            post.addRequestHeader(e.getKey(), e.getValue());
        }
    }
    final int expected = 302;
    final int status = httpClient.executeMethod(post);
    if (status != expected) {
        throw new HttpStatusCodeException(expected, status, "POST", url, HttpTestBase.getResponseBodyAsStream(post, 0));
    }
    String location = post.getResponseHeader("Location").getValue();
    post.releaseConnection();
    // simple check if host is missing
    if (!location.startsWith("http://")) {
        String host = HttpTestBase.HTTP_BASE_URL;
        int idx = host.indexOf('/', 8);
        if (idx > 0) {
            host = host.substring(0, idx);
        }
        location = host + location;
    }
    return location;
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) ArrayList(java.util.ArrayList) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) Map(java.util.Map)

Example 24 with FilePart

use of org.apache.commons.httpclient.methods.multipart.FilePart in project sling by apache.

the class SlingIntegrationTestClient method uploadToFileNode.

/** Upload to an file node structure, see SLING-168 */
public void uploadToFileNode(String url, File localFile, String fieldName, String typeHint) throws IOException {
    final Part[] parts = new Part[typeHint == null ? 1 : 2];
    parts[0] = new FilePart(fieldName, localFile);
    if (typeHint != null) {
        parts[1] = new StringPart(fieldName + "@TypeHint", typeHint);
    }
    final PostMethod post = new PostMethod(url);
    post.setFollowRedirects(false);
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    final int status = httpClient.executeMethod(post);
    final int expected = 200;
    if (status != expected) {
        throw new HttpStatusCodeException(expected, status, "POST", HttpTestBase.getResponseBodyAsStream(post, 0));
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart)

Example 25 with FilePart

use of org.apache.commons.httpclient.methods.multipart.FilePart in project sling by apache.

the class UpdateContentCommand method execute.

@Override
public Result<Void> execute() {
    PostMethod post = new PostMethod(getPath());
    try {
        List<Part> parts = new ArrayList<>();
        for (Map.Entry<String, Object> property : properties.entrySet()) {
            if (ProtectedNodes.exists(property.getKey())) {
                continue;
            }
            Object propValue = property.getValue();
            if (propValue instanceof String) {
                parts.add(new StringPart(property.getKey(), (String) propValue));
            } else if (property != null) {
                // TODO handle multi-valued properties
                System.err.println("Unable to handle property " + property.getKey() + " of type " + property.getValue().getClass());
            }
        }
        File f = new File(fileInfo.getLocation());
        if (f.isFile()) {
            parts.add(new FilePart(fileInfo.getName(), f));
        }
        post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));
        httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(repositoryInfo.getUsername(), repositoryInfo.getPassword()));
        httpClient.getParams().setAuthenticationPreemptive(true);
        int responseStatus = httpClient.executeMethod(post);
        return resultForResponseStatus(responseStatus);
    } catch (Exception e) {
        return AbstractResult.failure(new RepositoryException(e));
    } finally {
        post.releaseConnection();
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) ArrayList(java.util.ArrayList) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) RepositoryException(org.apache.sling.ide.transport.RepositoryException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) RepositoryException(org.apache.sling.ide.transport.RepositoryException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) Map(java.util.Map) File(java.io.File)

Aggregations

FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)27 Part (org.apache.commons.httpclient.methods.multipart.Part)25 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)23 PostMethod (org.apache.commons.httpclient.methods.PostMethod)20 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)18 HttpClient (org.apache.commons.httpclient.HttpClient)12 File (java.io.File)10 IOException (java.io.IOException)7 ByteArrayPartSource (org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource)7 Test (org.junit.Test)6 ArrayList (java.util.ArrayList)5 HttpState (org.apache.commons.httpclient.HttpState)4 FilePartSource (org.apache.commons.httpclient.methods.multipart.FilePartSource)4 HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)4 ServiceException (com.zimbra.common.service.ServiceException)3 Element (com.zimbra.common.soap.Element)3 SoapHttpTransport (com.zimbra.common.soap.SoapHttpTransport)3 HeaderElement (org.apache.commons.httpclient.HeaderElement)3 HttpException (org.apache.commons.httpclient.HttpException)3 PartSource (org.apache.commons.httpclient.methods.multipart.PartSource)3