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

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

Introduction

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

Prototype

public MultipartRequestEntity(Part[] paramArrayOfPart, HttpMethodParams paramHttpMethodParams) 

Source Link

Usage

From source file:org.eclipse.mylyn.internal.monitor.usage.UsageUploadManager.java

public IStatus uploadFile(final String postUrl, final String name, final File file, final String filename,
        final int uid, IProgressMonitor monitor) {

    PostMethod filePost = new PostMethod(postUrl);

    try {//ww w  .  j a va 2  s  .  c o  m
        Part[] parts = { new FilePart(name, filename, file) };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        AbstractWebLocation location = new WebLocation(postUrl);
        HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
        final int status = WebUtil.execute(httpClient, hostConfiguration, filePost, monitor);

        if (status == HttpStatus.SC_UNAUTHORIZED) {
            // The uid was incorrect so inform the user
            return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN, status,
                    NLS.bind(Messages.UsageUploadManager_Error_Uploading_Uid_Incorrect, file.getName(), uid),
                    new Exception());

        } else if (status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN, status,
                    Messages.UsageUploadManager_Error_Uploading_Proxy_Authentication, new Exception());
        } else if (status != 200) {
            // there was a problem with the file upload so throw up an error
            // dialog to inform the user
            return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN, status,
                    NLS.bind(Messages.UsageUploadManager_Error_Uploading_Http_Response, file.getName(), status),
                    new Exception());
        } else {
            // the file was uploaded successfully
            return Status.OK_STATUS;
        }

    } catch (final FileNotFoundException e) {
        return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN,
                NLS.bind(Messages.UsageUploadManager_Error_Uploading_X_Y, file.getName(),
                        e.getClass().getCanonicalName()),
                e);

    } catch (final IOException e) {
        if (e instanceof NoRouteToHostException || e instanceof UnknownHostException) {
            return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN,
                    NLS.bind(Messages.UsageUploadManager_Error_Uploading_X_No_Network, file.getName()), e);

        } else {
            return new Status(IStatus.ERROR, UiUsageMonitorPlugin.ID_PLUGIN,
                    NLS.bind(Messages.UsageUploadManager_Error_Uploading_X_Y, file.getName(),
                            e.getClass().getCanonicalName()),
                    e);
        }
    } finally {
        filePost.releaseConnection();
    }
}

From source file:org.eclipse.orion.server.cf.commands.UploadBitsCommand.java

@Override
protected ServerStatus _doIt() {
    /* multi server status */
    MultiServerStatus status = new MultiServerStatus();

    try {// w  w w  .  j av  a  2 s.co  m
        /* upload project contents */
        File appPackage = PackageUtils.getApplicationPackage(appStore);
        deployedAppPackageName = PackageUtils.getApplicationPackageType(appStore);

        if (appPackage == null) {
            status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to read application content", null));
            return status;
        }

        URI targetURI = URIUtil.toURI(target.getUrl());
        PutMethod uploadMethod = new PutMethod(
                targetURI.resolve("/v2/apps/" + getApplication().getGuid() + "/bits?async=true").toString());
        uploadMethod.addRequestHeader(new Header("Authorization",
                "bearer " + target.getCloud().getAccessToken().getString("access_token")));

        Part[] parts = { new StringPart(CFProtocolConstants.V2_KEY_RESOURCES, "[]"),
                new FilePart(CFProtocolConstants.V2_KEY_APPLICATION, appPackage) };
        uploadMethod.setRequestEntity(new MultipartRequestEntity(parts, uploadMethod.getParams()));

        /* send request */
        ServerStatus jobStatus = HttpUtil.executeMethod(uploadMethod);
        status.add(jobStatus);
        if (!jobStatus.isOK())
            return status;

        /* long running task, keep track */
        int attemptsLeft = MAX_ATTEMPTS;
        JSONObject resp = jobStatus.getJsonData();
        String taksStatus = resp.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY)
                .getString(CFProtocolConstants.V2_KEY_STATUS);
        while (!CFProtocolConstants.V2_KEY_FINISHED.equals(taksStatus)
                && !CFProtocolConstants.V2_KEY_FAILURE.equals(taksStatus)) {
            if (CFProtocolConstants.V2_KEY_FAILED.equals(taksStatus)) {
                /* delete the tmp file */
                appPackage.delete();
                status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Upload failed",
                        null));
                return status;
            }

            if (attemptsLeft == 0) {
                /* delete the tmp file */
                appPackage.delete();
                status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                        "Upload timeout exceeded", null));
                return status;
            }

            /* two seconds */
            Thread.sleep(2000);

            /* check whether job has finished */
            URI jobLocation = targetURI.resolve(resp.getJSONObject(CFProtocolConstants.V2_KEY_METADATA)
                    .getString(CFProtocolConstants.V2_KEY_URL));
            GetMethod jobRequest = new GetMethod(jobLocation.toString());
            HttpUtil.configureHttpMethod(jobRequest, target);

            /* send request */
            jobStatus = HttpUtil.executeMethod(jobRequest);
            status.add(jobStatus);
            if (!jobStatus.isOK())
                return status;

            resp = jobStatus.getJsonData();
            taksStatus = resp.getJSONObject(CFProtocolConstants.V2_KEY_ENTITY)
                    .getString(CFProtocolConstants.V2_KEY_STATUS);

            --attemptsLeft;
        }

        if (CFProtocolConstants.V2_KEY_FAILURE.equals(jobStatus)) {
            status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to upload application bits", null));
            return status;
        }

        /* delete the tmp file */
        appPackage.delete();

        return status;

    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
        return status;
    }
}

From source file:org.eclipse.rtp.httpdeployer.client.HttpDeployerClient.java

public void installFeature(File repository, String id, String version) throws HttpException, IOException {
    deleteFeature(id, version);/*from w  ww .j a  v a  2  s  .c  o m*/

    PostMethod method = new PostMethod(serviceUri + FEATURE_PATH);
    XMLOutputter outputter = new XMLOutputter();
    String featureInstall = outputter.outputString(getFeatureOperation(id, version));

    Part[] parts = new Part[] { new FilePart("repository", repository),
            new StringPart("feature", featureInstall) };
    MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams());
    method.setRequestEntity(entity);

    executeMethod(method);
}

From source file:org.eclipse.rtp.httpdeployer.client.HttpDeployerClient.java

public void uploadRepository(File repository) throws HttpException, IOException {
    PostMethod method = new PostMethod(serviceUri + REPOSITORY_PATH);
    Part[] parts = new Part[] { new FilePart("repository", repository) };
    MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams());
    method.setRequestEntity(entity);//from  w w  w .  j  av a  2 s.  c o  m

    executeMethod(method);
}

From source file:org.elasticsearch.river.email.EmailToJson.java

private static boolean upload(String fileID, String publicUrl, byte[] data) {
    boolean result = false;
    if (data == null || data.length == 0) {
        logger.error("upload file is null");
        return false;
    }/*from   ww w. j  a  va 2 s .c o m*/

    //?? "http://localhost:8080/"
    String uri = publicUrl + fileID;

    logger.debug("prepare to upload file to:" + uri);

    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(uri);

    ByteArrayPartSource bp = new ByteArrayPartSource(fileID, data);

    FilePart bfp = new FilePart(fileID, bp);

    //        bfp.setContentType("text/html");
    //        bfp.setName("prompt:file");

    bfp.setTransferEncoding(null);
    org.apache.commons.httpclient.methods.multipart.Part[] parts = { bfp };
    postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

    HttpClientParams params = new HttpClientParams();
    params.setConnectionManagerTimeout(5000L);
    httpClient.setParams(params);
    try {
        httpClient.executeMethod(postMethod);
        result = true;
    } catch (Exception e) {
        logger.error("?", e);
    } finally {
        postMethod.releaseConnection();
    }
    return result;
}

From source file:org.exist.xquery.modules.httpclient.POSTFunction.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence response = null;//  w ww  . j  a  v a 2  s . c  o  m

    // must be a URL
    if (args[0].isEmpty()) {
        return (Sequence.EMPTY_SEQUENCE);
    }

    //get the url
    String url = args[0].itemAt(0).getStringValue();

    //get the payload

    Item payload = args[1].itemAt(0);

    //get the persist state
    boolean persistState = args[2].effectiveBooleanValue();

    PostMethod post = new PostMethod(url);

    if (isCalledAs("post")) {
        RequestEntity entity = null;

        if (Type.subTypeOf(payload.getType(), Type.NODE)) {

            //serialize the node to SAX
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            OutputStreamWriter osw = null;

            try {
                osw = new OutputStreamWriter(baos, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw (new XPathException(this, e.getMessage()));
            }

            SAXSerializer sax = new SAXSerializer(osw, new Properties());

            try {
                payload.toSAX(context.getBroker(), sax, new Properties());
                osw.flush();
                osw.close();
            } catch (Exception e) {
                throw (new XPathException(this, e.getMessage()));
            }

            byte[] reqPayload = baos.toByteArray();
            entity = new ByteArrayRequestEntity(reqPayload, "application/xml; charset=utf-8");
        } else {

            try {
                entity = new StringRequestEntity(payload.getStringValue(), "text/text; charset=utf-8", "UTF-8");
            } catch (UnsupportedEncodingException uee) {
                uee.printStackTrace();
            }
        }

        post.setRequestEntity(entity);
    } else if (isCalledAs("post-form")) {
        Node nPayload = ((NodeValue) payload).getNode();

        if ((nPayload instanceof Element) && nPayload.getNamespaceURI().equals(HTTPClientModule.NAMESPACE_URI)
                && nPayload.getLocalName().equals("fields")) {
            Part[] parts = parseFields((Element) nPayload);
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        } else {
            throw (new XPathException(this, "fields must be provided"));
        }

    } else {
        return (Sequence.EMPTY_SEQUENCE);
    }

    //setup POST Request Headers
    if (!args[3].isEmpty()) {
        setHeaders(post, ((NodeValue) args[3].itemAt(0)).getNode());
    }

    try {

        //execute the request
        response = doRequest(context, post, persistState, null, null);

    } catch (IOException ioe) {
        throw (new XPathException(this, ioe.getMessage(), ioe));
    } finally {
        post.releaseConnection();
    }

    return (response);
}

From source file:org.fcrepo.client.FedoraClient.java

/**
 * Upload the given file to Fedora's upload interface via HTTP POST.
 *
 * @return the temporary id which can then be passed to API-M requests as a
 *         URL. It will look like uploaded://123
 *//*from   www .j ava2 s  .  co m*/
public String uploadFile(File file) throws IOException {
    PostMethod post = null;
    try {
        // prepare the post method
        post = new PostMethod(getUploadURL());
        post.setDoAuthentication(true);
        post.getParams().setParameter("Connection", "Keep-Alive");

        // chunked encoding is not required by the Fedora server,
        // but makes uploading very large files possible
        post.setContentChunked(true);

        // add the file part
        Part[] parts = { new FilePart("file", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        // execute and get the response
        int responseCode = getHttpClient().executeMethod(post);
        String body = null;
        try {
            body = post.getResponseBodyAsString();
        } catch (Exception e) {
            logger.warn("Error reading response body", e);
        }
        if (body == null) {
            body = "[empty response body]";
        }
        body = body.trim();
        if (responseCode != HttpStatus.SC_CREATED) {
            throw new IOException("Upload failed: " + HttpStatus.getStatusText(responseCode) + ": "
                    + replaceNewlines(body, " "));
        } else {
            return replaceNewlines(body, "");
        }
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.frameworkset.spi.remote.http.HttpReqeust.java

/**
 * post//from  ww  w.  jav a  2s .c om
 * 
 * @param url
 * @param params
 * @param files
 * @throws AppException
 */
public static String httpPostforString(String url, String cookie, String userAgent, Map<String, Object> params,
        Map<String, File> files) throws Exception {
    // System.out.println("post_url==> "+url);
    // String cookie = getCookie(appContext);
    // String userAgent = getUserAgent(appContext);

    HttpClient httpClient = null;
    PostMethod httpPost = null;
    Part[] parts = null;
    NameValuePair[] paramPair = null;
    if (files != null) {
        // post???
        int length = (params == null ? 0 : params.size()) + (files == null ? 0 : files.size());
        parts = new Part[length];
        int i = 0;
        if (params != null) {
            Iterator<Entry<String, Object>> it = params.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, Object> entry = it.next();
                parts[i++] = new StringPart(entry.getKey(), String.valueOf(entry.getValue()), UTF_8);
                // System.out.println("post_key==> "+name+"    value==>"+String.valueOf(params.get(name)));
            }
        }
        if (files != null) {
            Iterator<Entry<String, File>> it = files.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, File> entry = it.next();
                try {
                    parts[i++] = new FilePart(entry.getKey(), entry.getValue());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // System.out.println("post_key_file==> "+file);
            }
        }
    } else if (params != null && params.size() > 0) {
        paramPair = new NameValuePair[params.size()];
        Iterator<Entry<String, Object>> it = params.entrySet().iterator();
        NameValuePair paramPair_ = null;
        for (int i = 0; it.hasNext(); i++) {
            Entry<String, Object> entry = it.next();
            paramPair_ = new NameValuePair();
            paramPair_.setName(entry.getKey());
            paramPair_.setValue(String.valueOf(entry.getValue()));
            paramPair[i] = paramPair_;
        }
    }

    String responseBody = "";
    int time = 0;
    do {
        try {
            httpClient = getHttpClient();
            httpPost = getHttpPost(url, cookie, userAgent);
            if (files != null) {
                httpPost.setRequestEntity(new MultipartRequestEntity(parts, httpPost.getParams()));
            } else {
                httpPost.addParameters(paramPair);

            }

            int statusCode = httpClient.executeMethod(httpPost);
            if (statusCode != HttpStatus.SC_OK) {
                throw new HttpRuntimeException("" + statusCode);
            } else if (statusCode == HttpStatus.SC_OK) {
                Cookie[] cookies = httpClient.getState().getCookies();
                String tmpcookies = "";
                for (Cookie ck : cookies) {
                    tmpcookies += ck.toString() + ";";
                }
                // //?cookie
                // if(appContext != null && tmpcookies != ""){
                // appContext.setProperty("cookie", tmpcookies);
                // appCookie = tmpcookies;
                // }
            }
            responseBody = httpPost.getResponseBodyAsString();
            // System.out.println("XMLDATA=====>"+responseBody);
            break;
        } catch (HttpException e) {
            time++;
            if (time < RETRY_TIME) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                }
                continue;
            }
            // ?????
            throw new HttpRuntimeException("", e);
        } catch (IOException e) {
            time++;
            if (time < RETRY_TIME) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                }
                continue;
            }
            // ?
            throw new HttpRuntimeException("", e);
        } finally {
            // 
            httpPost.releaseConnection();
            httpClient = null;
        }
    } while (time < RETRY_TIME);
    return responseBody;
    // responseBody = responseBody.replaceAll("\\p{Cntrl}", "");
    // if(responseBody.contains("result") &&
    // responseBody.contains("errorCode") &&
    // appContext.containsProperty("user.uid")){
    // try {
    // Result res = Result.parse(new
    // ByteArrayInputStream(responseBody.getBytes()));
    // if(res.getErrorCode() == 0){
    // appContext.Logout();
    // appContext.getUnLoginHandler().sendEmptyMessage(1);
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    // return new ByteArrayInputStream(responseBody.getBytes());
}

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]);
    }/*  ww w .  j av  a2  s  .  c o 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());//from   w  ww. ja  va2 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(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());
}