Example usage for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity writeRequest

List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity writeRequest

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity writeRequest.

Prototype

public void writeRequest(OutputStream paramOutputStream) throws IOException 

Source Link

Usage

From source file:com.ning.http.client.providers.NettyAsyncHttpProvider.java

@SuppressWarnings("deprecation")
HttpRequest construct(Request request, HttpMethod m, Url url) throws IOException {
    String host = url.getHost();/*from  ww  w . j  a  v  a  2  s  . co m*/

    if (request.getVirtualHost() != null) {
        host = request.getVirtualHost();
    }

    HttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, m, url.getPath());
    nettyRequest.setHeader(HttpHeaders.Names.HOST, host + ":" + url.getPort());

    Headers h = request.getHeaders();
    if (h != null) {
        Iterator<Pair<String, String>> i = h.iterator();
        Pair<String, String> p;
        while (i.hasNext()) {
            p = i.next();
            if ("host".equalsIgnoreCase(p.getFirst())) {
                continue;
            }
            String key = p.getFirst() == null ? "" : p.getFirst();
            String value = p.getSecond() == null ? "" : p.getSecond();

            nettyRequest.setHeader(key, value);
        }
    }

    String ka = config.getKeepAlive() ? "keep-alive" : "close";
    nettyRequest.setHeader(HttpHeaders.Names.CONNECTION, ka);
    if (config.getProxyServer() != null) {
        nettyRequest.setHeader("Proxy-Connection", ka);
    }

    if (config.getUserAgent() != null) {
        nettyRequest.setHeader("User-Agent", config.getUserAgent());
    }

    if (request.getCookies() != null && !request.getCookies().isEmpty()) {
        CookieEncoder httpCookieEncoder = new CookieEncoder(false);
        Iterator<Cookie> ic = request.getCookies().iterator();
        Cookie c;
        org.jboss.netty.handler.codec.http.Cookie cookie;
        while (ic.hasNext()) {
            c = ic.next();
            cookie = new DefaultCookie(c.getName(), c.getValue());
            cookie.setPath(c.getPath());
            cookie.setMaxAge(c.getMaxAge());
            cookie.setDomain(c.getDomain());
            httpCookieEncoder.addCookie(cookie);
        }
        nettyRequest.setHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode());
    }

    if (config.isCompressionEnabled()) {
        nettyRequest.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    }

    switch (request.getType()) {
    case POST:
        if (request.getByteData() != null) {
            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
                    String.valueOf(request.getByteData().length));
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData()));
        } else if (request.getStringData() != null) {
            // TODO: Not sure we need to reconfigure that one.
            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
                    String.valueOf(request.getStringData().length()));
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), "UTF-8"));
        } else if (request.getStreamData() != null) {
            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
                    String.valueOf(request.getStreamData().available()));
            byte[] b = new byte[(int) request.getStreamData().available()];
            request.getStreamData().read(b);
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(b));
        } else if (request.getParams() != null) {
            StringBuilder sb = new StringBuilder();
            for (final Entry<String, String> param : request.getParams().entrySet()) {
                sb.append(param.getKey());
                sb.append("=");
                sb.append(param.getValue());
                sb.append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length()));
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(sb.toString().getBytes()));
        } else if (request.getParts() != null) {
            int lenght = computeAndSetContentLength(request, nettyRequest);

            if (lenght == -1) {
                lenght = MAX_BUFFERRED_BYTES;
            }

            /**
             * This is quite ugly to mix and match with Apache Client,
             * but the fastest way for now
             * TODO: Remove this dependency.
             */
            PostMethod post = new PostMethod(request.getUrl());
            MultipartRequestEntity mre = createMultipartRequestEntity(request.getParts(), post.getParams());

            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
            nettyRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength()));

            ChannelBuffer b = ChannelBuffers.dynamicBuffer((int) lenght);
            mre.writeRequest(new ChannelBufferOutputStream(b));
            nettyRequest.setContent(b);
        } else if (request.getEntityWriter() != null) {
            computeAndSetContentLength(request, nettyRequest);

            ChannelBuffer b = ChannelBuffers.dynamicBuffer((int) request.getLength());
            request.getEntityWriter().writeEntity(new ChannelBufferOutputStream(b));
            nettyRequest.setContent(b);
        }
        break;
    case PUT:
        if (request.getByteData() != null) {
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getByteData()));
        } else if (request.getStringData() != null) {
            nettyRequest.setContent(ChannelBuffers.copiedBuffer(request.getStringData(), "UTF-8"));
        }
        break;
    }

    if (nettyRequest.getHeader(HttpHeaders.Names.CONTENT_TYPE) == null) {
        nettyRequest.setHeader(HttpHeaders.Names.CONTENT_TYPE, "txt/html; charset=utf-8");
    }
    if (log.isDebugEnabled())
        log.debug("Constructed request: " + nettyRequest);
    return nettyRequest;
}

From source file:org.activiti.rest.HttpMultipartRepresentation.java

public void processStreamAndSetMediaType(final String fileName, InputStream fileStream,
        Map<String, String> additionalFormFields) throws IOException {
    // Copy the stream in a bytearray to get the length
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    IOUtils.copy(fileStream, output);/*  ww  w .  j a v  a2  s .co m*/

    final int length = output.toByteArray().length;
    final InputStream stream = new ByteArrayInputStream(output.toByteArray());

    List<Part> parts = new ArrayList<Part>();

    // Filepart is based on in-memory stream an file-name rather than an actual file
    FilePart filePart = new FilePart(fileName, new PartSource() {
        @Override
        public long getLength() {
            return length;
        }

        @Override
        public String getFileName() {
            return fileName;
        }

        @Override
        public InputStream createInputStream() throws IOException {
            return stream;
        }
    });
    parts.add(filePart);

    if (additionalFormFields != null && !additionalFormFields.isEmpty()) {
        for (Entry<String, String> field : additionalFormFields.entrySet()) {
            parts.add(new StringPart(field.getKey(), field.getValue()));
        }
    }

    MultipartRequestEntity entity = new MultipartRequestEntity(parts.toArray(new Part[] {}),
            new HttpMethodParams());

    // Let the entity write the raw multipart to a bytearray, which is used as a source
    // for the input-stream returned by this Representation
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    entity.writeRequest(os);
    setMediaType(new MediaType(entity.getContentType()));
    setStream(new ByteArrayInputStream(os.toByteArray()));
}

From source file:org.alfresco.repo.web.scripts.custommodel.CustomModelImportTest.java

public PostRequest buildMultipartPostRequest(File file) throws IOException {
    Part[] parts = { new FilePart("filedata", file.getName(), file, "application/zip", null) };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    multipartRequestEntity.writeRequest(os);

    PostRequest postReq = new PostRequest(UPLOAD_URL, os.toByteArray(),
            multipartRequestEntity.getContentType());
    return postReq;
}

From source file:org.alfresco.rest.api.tests.util.MultiPartBuilder.java

public MultiPartRequest build() throws IOException {
    List<Part> parts = new ArrayList<>();

    if (fileData != null) {
        FilePart fp = new FilePart("filedata", fileData.getFileName(), fileData.getFile(),
                fileData.getMimetype(), null);
        // Get rid of the default values added upon FilePart instantiation
        fp.setCharSet(fileData.getEncoding());
        fp.setContentType(fileData.getMimetype());
        parts.add(fp);//from ww  w  .  j  a  va 2 s.c  om
        addPartIfNotNull(parts, "name", fileData.getFileName());
    }
    addPartIfNotNull(parts, "relativepath", relativePath);
    addPartIfNotNull(parts, "updatenoderef", updateNodeRef);
    addPartIfNotNull(parts, "description", description);
    addPartIfNotNull(parts, "contenttype", contentTypeQNameStr);
    addPartIfNotNull(parts, "aspects", getCommaSeparated(aspects));
    addPartIfNotNull(parts, "majorversion", majorVersion);
    addPartIfNotNull(parts, "overwrite", overwrite);
    addPartIfNotNull(parts, "autorename", autoRename);
    addPartIfNotNull(parts, "nodetype", nodeType);
    addPartIfNotNull(parts, "renditions", getCommaSeparated(renditionIds));

    if (!properties.isEmpty()) {
        for (Entry<String, String> prop : properties.entrySet()) {
            parts.add(new StringPart(prop.getKey(), prop.getValue()));
        }
    }

    MultipartRequestEntity req = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]),
            new HttpMethodParams());

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    req.writeRequest(os);

    return new MultiPartRequest(os.toByteArray(), req.getContentType(), req.getContentLength());
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

private String sendPostData(PostMethod post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();
    // Check if we should do a multipart/form-data or an
    // application/x-www-form-urlencoded post request
    if (getUseMultipartForPost()) {
        // If a content encoding is specified, we use that as the
        // encoding of any parameter values
        String contentEncoding = getContentEncoding();
        if (isNullOrEmptyTrimmed(contentEncoding)) {
            contentEncoding = null;//from   w w w.j  a  v  a  2s. c om
        }

        final boolean browserCompatible = getDoBrowserCompatibleMultipart();
        // We don't know how many entries will be skipped
        List<PartBase> partlist = new ArrayList<>();
        // Create the parts
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            StringPart part = new StringPart(arg.getName(), arg.getValue(), contentEncoding);
            if (browserCompatible) {
                part.setTransferEncoding(null);
                part.setContentType(null);
            }
            partlist.add(part);
        }

        // Add any files
        for (HTTPFileArg file : files) {
            File inputFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            // We do not know the char set of the file to be uploaded, so we set it to null
            ViewableFilePart filePart = new ViewableFilePart(file.getParamName(), inputFile, file.getMimeType(),
                    null);
            filePart.setCharSet(null); // We do not know what the char set of the file is
            partlist.add(filePart);
        }

        // Set the multipart for the post
        int partNo = partlist.size();
        Part[] parts = partlist.toArray(new Part[partNo]);
        MultipartRequestEntity multiPart = new MultipartRequestEntity(parts, post.getParams());
        post.setRequestEntity(multiPart);

        // Set the content type
        String multiPartContentType = multiPart.getContentType();
        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, multiPartContentType);

        // If the Multipart is repeatable, we can send it first to
        // our own stream, without the actual file content, so we can return it
        if (multiPart.isRepeatable()) {
            // For all the file multiparts, we must tell it to not include
            // the actual file content
            for (int i = 0; i < partNo; i++) {
                if (parts[i] instanceof ViewableFilePart) {
                    ((ViewableFilePart) parts[i]).setHideFileData(true); // .sendMultipartWithoutFileContent(bos);
                }
            }
            // Write the request to our own stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            multiPart.writeRequest(bos);
            bos.flush();
            // We get the posted bytes using the encoding used to create it
            postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient
                    : contentEncoding));
            bos.close();

            // For all the file multiparts, we must revert the hiding of
            // the actual file content
            for (int i = 0; i < partNo; i++) {
                if (parts[i] instanceof ViewableFilePart) {
                    ((ViewableFilePart) parts[i]).setHideFileData(false);
                }
            }
        } else {
            postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
        }
    } else {
        // Check if the header manager had a content type header
        // This allows the user to specify his own content-type for a POST request
        Header contentTypeHeader = post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null
                && contentTypeHeader.getValue().length() > 0;
        // If there are no arguments, we can send a file as the body of the request
        // TODO: needs a multiple file upload scenerio
        if (!hasArguments() && getSendFileAsPostBody()) {
            // If getSendFileAsPostBody returned true, it's sure that file is not null
            HTTPFileArg file = files[0];
            if (!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                if (file.getMimeType() != null && file.getMimeType().length() > 0) {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }

            FileRequestEntity fileRequestEntity = new FileRequestEntity(new File(file.getPath()), null);
            post.setRequestEntity(fileRequestEntity);

            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // In a post request which is not multipart, we only support
            // parameters, no file upload is allowed

            // If a content encoding is specified, we set it as http parameter, so that
            // the post body will be encoded in the specified content encoding
            String contentEncoding = getContentEncoding();
            boolean haveContentEncoding = false;
            if (isNullOrEmptyTrimmed(contentEncoding)) {
                contentEncoding = null;
            } else {
                post.getParams().setContentCharset(contentEncoding);
                haveContentEncoding = true;
            }

            // If none of the arguments have a name specified, we
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // Allow the mimetype of the file to control the content type
                // This is not obvious in GUI if you are not uploading any files,
                // but just sending the content of nameless parameters
                // TODO: needs a multiple file upload scenerio
                if (!hasContentTypeHeader) {
                    HTTPFileArg file = files.length > 0 ? files[0] : null;
                    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else {
                        // TODO - is this the correct default?
                        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                                HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                    }
                }

                // Just append all the parameter values, and use that as the post body
                StringBuilder postBody = new StringBuilder();
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    String value;
                    if (haveContentEncoding) {
                        value = arg.getEncodedValue(contentEncoding);
                    } else {
                        value = arg.getEncodedValue();
                    }
                    postBody.append(value);
                }
                StringRequestEntity requestEntity = new StringRequestEntity(postBody.toString(),
                        post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue(), contentEncoding);
                post.setRequestEntity(requestEntity);
            } else {
                // It is a normal post request, with parameter names and values

                // Set the content type
                if (!hasContentTypeHeader) {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                // Add the parameters
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    // The HTTPClient always urlencodes both name and value,
                    // so if the argument is already encoded, we have to decode
                    // it before adding it to the post request
                    String parameterName = arg.getName();
                    if (arg.isSkippable(parameterName)) {
                        continue;
                    }
                    String parameterValue = arg.getValue();
                    if (!arg.isAlwaysEncoded()) {
                        // The value is already encoded by the user
                        // Must decode the value now, so that when the
                        // httpclient encodes it, we end up with the same value
                        // as the user had entered.
                        String urlContentEncoding = contentEncoding;
                        if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
                            // Use the default encoding for urls
                            urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
                        }
                        parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
                        parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
                    }
                    // Add the parameter, httpclient will urlencode it
                    post.addParameter(parameterName, parameterValue);
                }

                /*
                //                    // Alternative implementation, to make sure that HTTPSampler and HTTPSampler2
                //                    // sends the same post body.
                //
                //                    // Only include the content char set in the content-type header if it is not
                //                    // an APPLICATION_X_WWW_FORM_URLENCODED content type
                //                    String contentCharSet = null;
                //                    if(!post.getRequestHeader(HEADER_CONTENT_TYPE).getValue().equals(APPLICATION_X_WWW_FORM_URLENCODED)) {
                //                        contentCharSet = post.getRequestCharSet();
                //                    }
                //                    StringRequestEntity requestEntity = new StringRequestEntity(getQueryString(contentEncoding), post.getRequestHeader(HEADER_CONTENT_TYPE).getValue(), contentCharSet);
                //                    post.setRequestEntity(requestEntity);
                */
            }

            // If the request entity is repeatable, we can send it first to
            // our own stream, so we can return it
            if (post.getRequestEntity().isRepeatable()) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                post.getRequestEntity().writeRequest(bos);
                bos.flush();
                // We get the posted bytes using the encoding used to create it
                postedBody.append(new String(bos.toByteArray(), post.getRequestCharSet()));
                bos.close();
            } else {
                postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
            }
        }
    }
    // Set the content length
    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH,
            Long.toString(post.getRequestEntity().getContentLength()));

    return postedBody.toString();
}

From source file:org.geoserver.importer.rest.ImportTaskControllerTest.java

@Test
public void testDeleteTask() throws Exception {
    MockHttpServletResponse resp = postAsServletResponse(RestBaseController.ROOT_PATH + "/imports", "");
    assertEquals(201, resp.getStatus());
    assertNotNull(resp.getHeader("Location"));

    String[] split = resp.getHeader("Location").split("/");
    Integer id = Integer.parseInt(split[split.length - 1]);

    ImportContext context = importer.getContext(id);

    File dir = unpack("shape/archsites_epsg_prj.zip");
    unpack("shape/bugsites_esri_prj.tar.gz", dir);

    new File(dir, "extra.file").createNewFile();
    File[] files = dir.listFiles();
    Part[] parts = new Part[files.length];
    for (int i = 0; i < files.length; i++) {
        parts[i] = new FilePart(files[i].getName(), files[i]);
    }//from   ww  w.  j a  va2  s .  co m

    MultipartRequestEntity multipart = new MultipartRequestEntity(parts, new PostMethod().getParams());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    multipart.writeRequest(bout);

    MockHttpServletRequest req = createRequest(RestBaseController.ROOT_PATH + "/imports/" + id + "/tasks");
    req.setContentType(multipart.getContentType());
    req.addHeader("Content-Type", multipart.getContentType());
    req.setMethod("POST");
    req.setContent(bout.toByteArray());
    resp = dispatch(req);

    context = importer.getContext(context.getId());
    assertEquals(2, context.getTasks().size());

    req = createRequest(RestBaseController.ROOT_PATH + "/imports/" + id + "/tasks/1");
    req.setMethod("DELETE");
    resp = dispatch(req);
    assertEquals(204, resp.getStatus());

    context = importer.getContext(context.getId());
    assertEquals(1, context.getTasks().size());
}

From source file:org.geoserver.importer.rest.ImportTaskControllerTest.java

@Test
public void testPostMultiPartFormData() throws Exception {
    MockHttpServletResponse resp = postAsServletResponse(RestBaseController.ROOT_PATH + "/imports", "");
    assertEquals(201, resp.getStatus());
    assertNotNull(resp.getHeader("Location"));

    String[] split = resp.getHeader("Location").split("/");
    Integer id = Integer.parseInt(split[split.length - 1]);
    ImportContext context = importer.getContext(id);
    assertNull(context.getData());/*  w  w  w.j a v a 2s  . c om*/
    assertTrue(context.getTasks().isEmpty());

    File dir = unpack("shape/archsites_epsg_prj.zip");

    Part[] parts = new Part[] { new FilePart("archsites.shp", new File(dir, "archsites.shp")),
            new FilePart("archsites.dbf", new File(dir, "archsites.dbf")),
            new FilePart("archsites.shx", new File(dir, "archsites.shx")),
            new FilePart("archsites.prj", new File(dir, "archsites.prj")) };

    MultipartRequestEntity multipart = new MultipartRequestEntity(parts, new PostMethod().getParams());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    multipart.writeRequest(bout);

    MockHttpServletRequest req = createRequest(RestBaseController.ROOT_PATH + "/imports/" + id + "/tasks");
    req.setContentType(multipart.getContentType());
    req.addHeader("Content-Type", multipart.getContentType());
    req.setMethod("POST");
    req.setContent(bout.toByteArray());
    resp = dispatch(req);

    context = importer.getContext(context.getId());
    assertNull(context.getData());
    assertEquals(1, context.getTasks().size());

    ImportTask task = context.getTasks().get(0);
    assertTrue(task.getData() instanceof SpatialFile);
    assertEquals(ImportTask.State.READY, task.getState());
}

From source file:org.geoserver.importer.rest.RESTDataTest.java

int postNewTaskAsMultiPartForm(int imp, String data) throws Exception {
    File dir = unpack(data);//  www.  j  a va2s.c  om

    List<Part> parts = new ArrayList<Part>();
    for (File f : dir.listFiles()) {
        parts.add(new FilePart(f.getName(), f));
    }
    MultipartRequestEntity multipart = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]),
            new PostMethod().getParams());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    multipart.writeRequest(bout);

    MockHttpServletRequest req = createRequest("/rest/imports/" + imp + "/tasks");
    req.setContentType(multipart.getContentType());
    req.addHeader("Content-Type", multipart.getContentType());
    req.setMethod("POST");
    req.setBodyContent(bout.toByteArray());

    MockHttpServletResponse resp = dispatch(req);
    assertEquals(201, resp.getStatusCode());
    assertNotNull(resp.getHeader("Location"));

    assertTrue(resp.getHeader("Location").matches(".*/imports/" + imp + "/tasks/\\d"));
    assertEquals("application/json", resp.getContentType());

    JSONObject json = (JSONObject) json(resp);

    JSONObject task = json.getJSONObject("task");
    return task.getInt("id");
}

From source file:org.geoserver.importer.rest.TaskResourceTest.java

public void testDeleteTask() throws Exception {
    MockHttpServletResponse resp = postAsServletResponse("/rest/imports", "");
    assertEquals(201, resp.getStatusCode());
    assertNotNull(resp.getHeader("Location"));

    String[] split = resp.getHeader("Location").split("/");
    Integer id = Integer.parseInt(split[split.length - 1]);

    ImportContext context = importer.getContext(id);

    File dir = unpack("shape/archsites_epsg_prj.zip");
    unpack("shape/bugsites_esri_prj.tar.gz", dir);

    new File(dir, "extra.file").createNewFile();
    File[] files = dir.listFiles();
    Part[] parts = new Part[files.length];
    for (int i = 0; i < files.length; i++) {
        parts[i] = new FilePart(files[i].getName(), files[i]);
    }//from   w w w. j av  a  2 s.c o  m

    MultipartRequestEntity multipart = new MultipartRequestEntity(parts, new PostMethod().getParams());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    multipart.writeRequest(bout);

    MockHttpServletRequest req = createRequest("/rest/imports/" + id + "/tasks");
    req.setContentType(multipart.getContentType());
    req.addHeader("Content-Type", multipart.getContentType());
    req.setMethod("POST");
    req.setBodyContent(bout.toByteArray());
    resp = dispatch(req);

    context = importer.getContext(context.getId());
    assertEquals(2, context.getTasks().size());

    req = createRequest("/rest/imports/" + id + "/tasks/1");
    req.setMethod("DELETE");
    resp = dispatch(req);
    assertEquals(204, resp.getStatusCode());

    context = importer.getContext(context.getId());
    assertEquals(1, context.getTasks().size());
}

From source file:org.geoserver.importer.rest.TaskResourceTest.java

public void testPostMultiPartFormData() throws Exception {
    MockHttpServletResponse resp = postAsServletResponse("/rest/imports", "");
    assertEquals(201, resp.getStatusCode());
    assertNotNull(resp.getHeader("Location"));

    String[] split = resp.getHeader("Location").split("/");
    Integer id = Integer.parseInt(split[split.length - 1]);
    ImportContext context = importer.getContext(id);
    assertNull(context.getData());//from  ww w.ja v a 2 s  .c  om
    assertTrue(context.getTasks().isEmpty());

    File dir = unpack("shape/archsites_epsg_prj.zip");

    Part[] parts = new Part[] { new FilePart("archsites.shp", new File(dir, "archsites.shp")),
            new FilePart("archsites.dbf", new File(dir, "archsites.dbf")),
            new FilePart("archsites.shx", new File(dir, "archsites.shx")),
            new FilePart("archsites.prj", new File(dir, "archsites.prj")) };

    MultipartRequestEntity multipart = new MultipartRequestEntity(parts, new PostMethod().getParams());

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    multipart.writeRequest(bout);

    MockHttpServletRequest req = createRequest("/rest/imports/" + id + "/tasks");
    req.setContentType(multipart.getContentType());
    req.addHeader("Content-Type", multipart.getContentType());
    req.setMethod("POST");
    req.setBodyContent(bout.toByteArray());
    resp = dispatch(req);

    context = importer.getContext(context.getId());
    assertNull(context.getData());
    assertEquals(1, context.getTasks().size());

    ImportTask task = context.getTasks().get(0);
    assertTrue(task.getData() instanceof SpatialFile);
    assertEquals(ImportTask.State.READY, task.getState());
}