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.xwiki.test.storage.framework.StoreTestUtils.java

public static HttpMethod doUpload(final String address, final UsernamePasswordCredentials userNameAndPassword,
        final Map<String, byte[]> uploads) throws IOException {
    final HttpClient client = new HttpClient();
    final PostMethod method = new PostMethod(address);

    if (userNameAndPassword != null) {
        client.getState().setCredentials(AuthScope.ANY, userNameAndPassword);
        client.getParams().setAuthenticationPreemptive(true);
    }/*from   w ww . j  a v a 2s .  c  o m*/

    Part[] parts = new Part[uploads.size()];
    int i = 0;
    for (Map.Entry<String, byte[]> e : uploads.entrySet()) {
        parts[i++] = new FilePart("filepath", new ByteArrayPartSource(e.getKey(), e.getValue()));
    }
    MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams());
    method.setRequestEntity(entity);

    client.executeMethod(method);
    return method;
}

From source file:org.zend.usagedata.internal.recording.uploading.BasicUploader.java

/**
 * This method does the heavy lifting when it comes to downloads.
 * /*w  w  w.jav  a  2s  .co m*/
 * I can envision a time when we may want to upload something other than files.
 * We may, for example, want to upload an in-memory representation of the files.
 * For now, in the spirit of having something that works is better than
 * overengineering something you may not need, we're just dealing with files.
 * 
 * @param monitor
 *            an instance of something that implements
 *            {@link IProgressMonitor}. Must not be <code>null</code>.
 * @throws Exception 
 */
UploadResult doUpload(IProgressMonitor monitor) throws Exception {
    monitor.beginTask("Upload", getUploadParameters().getFiles().length + 3); //$NON-NLS-1$
    /*
     * The files that we have been provided with were determined while the recorder
     * was suspended. We should be safe to work with these files without worrying
     * that other threads are messing with them. We do need to consider that other
     * processes running outside of our JVM may be messing with these files and
     * anticipate errors accordingly.
     */

    // TODO Does it make sense to create a custom exception for this?
    if (!hasUserAuthorizedUpload())
        throw new Exception("User has not authorized upload."); //$NON-NLS-1$

    /*
     * There appears to be some mechanism on some versions of HttpClient that
     * allows the insertion of compression technology. For now, we don't worry
     * about compressing our output; we can worry about that later.
     */
    PostMethod post = new PostMethod(getSettings().getUploadUrl());

    post.setRequestHeader(HTTP_USERID, getSettings().getUserId());
    post.setRequestHeader(HTTP_WORKSPACEID, getSettings().getWorkspaceId());
    post.setRequestHeader(HTTP_TIME, String.valueOf(System.currentTimeMillis()));
    post.setRequestHeader(USER_AGENT, getSettings().getUserAgent());

    boolean loggingServerActivity = getSettings().isLoggingServerActivity();
    if (loggingServerActivity) {
        post.setRequestHeader("LOGGING", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    post.setRequestEntity(new MultipartRequestEntity(getFileParts(monitor), post.getParams()));
    post.setRequestHeader(CONTENT_LENGTH, String.valueOf(post.getRequestEntity().getContentLength()));
    // Configure the HttpClient to timeout after one minute.
    HttpClientParams httpParameters = new HttpClientParams();
    httpParameters.setSoTimeout(getSocketTimeout()); // "So" means "socket"; who knew?

    monitor.worked(1);

    int result = new HttpClient(httpParameters).executeMethod(post);

    handleServerResponse(post);

    monitor.worked(1);

    post.releaseConnection();

    // Check the result. HTTP return code of 200 means success.
    if (result == 200) {
        for (File file : getUploadParameters().getFiles()) {
            // TODO what if file delete fails?
            if (file.exists())
                file.delete();
        }
    }

    monitor.worked(1);

    monitor.done();

    return new UploadResult(result);
}

From source file:oscar.oscarBilling.ca.bc.Teleplan.TeleplanAPI.java

private TeleplanResponse processRequest(String url, Part[] parts) {
    TeleplanResponse tr = null;//w ww .  j  av a 2  s. co  m
    try {
        PostMethod filePost = new PostMethod(url);
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        httpclient.executeMethod(filePost);

        InputStream in = filePost.getResponseBodyAsStream();
        tr = new TeleplanResponse();
        tr.processResponseStream(in);
        TeleplanResponseDAO trDAO = new TeleplanResponseDAO();
        trDAO.save(tr);

    } catch (Exception e) {
        MiscUtils.getLogger().error("Error", e);
    }
    return tr;
}

From source file:pl.nask.hsn2.connector.CuckooRESTConnector.java

public final long sendFile(File file, Set<NameValuePair> cuckooParams)
        throws CuckooException, ResourceException {

    PostMethod post = new PostMethod(cuckooURL + SEND_FILE_TASK);
    try {//from www.  ja va2s.com
        int size = cuckooParams.size();
        Part[] parts = new Part[size + 1];
        int i = 0;
        for (NameValuePair pair : cuckooParams) {
            parts[i] = new StringPart(pair.getName(), pair.getValue());
            i++;
        }
        parts[i] = new FilePart("file", file);

        RequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
        post.setRequestEntity(entity);
        return sendPost(post);
    } catch (FileNotFoundException e) {
        LOGGER.error("This should never happen!", e);
        throw new ResourceException(e.getMessage(), e);
    }

}

From source file:pl.umk.mat.zawodyweb.compiler.classes.LanguageMAIN.java

/**
 * Sprawdza rozwizanie na input//from www  . j  a v  a 2  s. com
 * @param path kod rdowy
 * @param input w formacie:
 *              <pre>c=NUMER_KONKURSU<br/>t=NUMER_ZADANIA<br/>m=MAX_POINTS</pre>
 * @return
 */
@Override
public TestOutput runTest(String path, TestInput input) {
    TestOutput result = new TestOutput(null);

    Integer contest_id = null;
    Integer task_id = null;
    Integer max_points = null;
    try {
        try {
            Matcher matcher = null;

            matcher = Pattern.compile("c=([0-9]+)").matcher(input.getInputText());
            if (matcher.find()) {
                contest_id = Integer.valueOf(matcher.group(1));
            }

            matcher = Pattern.compile("t=([0-9]+)").matcher(input.getInputText());
            if (matcher.find()) {
                task_id = Integer.valueOf(matcher.group(1));
            }

            matcher = Pattern.compile("m=([0-9]+)").matcher(input.getInputText());
            if (matcher.find()) {
                max_points = Integer.valueOf(matcher.group(1));
            }

            if (contest_id == null) {
                throw new IllegalArgumentException("task_id == null");
            }
            if (task_id == null) {
                throw new IllegalArgumentException("task_id == null");
            }
        } catch (PatternSyntaxException ex) {
            throw new IllegalArgumentException(ex);
        } catch (NumberFormatException ex) {
            throw new IllegalArgumentException(ex);
        } catch (IllegalStateException ex) {
            throw new IllegalArgumentException(ex);
        }
    } catch (IllegalArgumentException e) {
        logger.error("Exception when parsing input", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("MAIN IllegalArgumentException");
        return result;
    }
    logger.debug("Contest id = " + contest_id);
    logger.debug("Task id = " + task_id);
    logger.debug("Max points = " + max_points);

    String loginUrl = "http://main.edu.pl/pl/login";
    String login = properties.getProperty("main_edu_pl.login");
    String password = properties.getProperty("main_edu_pl.password");

    HttpClient client = new HttpClient();

    HttpClientParams params = client.getParams();
    params.setParameter("http.useragent", "Opera/9.64 (Windows NT 6.0; U; pl) Presto/2.1.1");
    //params.setParameter("http.protocol.handle-redirects", true);
    client.setParams(params);
    /* logowanie */
    logger.debug("Logging in");
    PostMethod postMethod = new PostMethod(loginUrl);
    NameValuePair[] dataLogging = { new NameValuePair("auth", "1"), new NameValuePair("login", login),
            new NameValuePair("pass", password) };
    postMethod.setRequestBody(dataLogging);
    try {
        client.executeMethod(postMethod);
        if (Pattern.compile("Logowanie udane").matcher(postMethod.getResponseBodyAsString(1024 * 1024))
                .find() == false) {
            logger.error("Unable to login (" + login + ":" + password + ")");
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setOutputText("Logging in failed");
            postMethod.releaseConnection();
            return result;
        }
    } catch (HttpException e) {
        logger.error("Exception when logging in", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("HttpException");
        postMethod.releaseConnection();
        return result;
    } catch (IOException e) {
        logger.error("Exception when logging in", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("IOException");
        postMethod.releaseConnection();
        return result;
    }
    postMethod.releaseConnection();

    /* wchodzenie na stron z wysyaniem zada i pobieranie pl z hidden */
    logger.debug("Getting submit page");
    ArrayList<Part> values = new ArrayList<Part>();
    try {
        GetMethod getMethod = new GetMethod("http://main.edu.pl/user.phtml?op=submit&m=insert&c=" + contest_id);
        client.executeMethod(getMethod);
        String response = getMethod.getResponseBodyAsString(1024 * 1024);
        getMethod.releaseConnection();

        Matcher tagMatcher = Pattern.compile("<input[^>]*>").matcher(response);
        Pattern namePattern = Pattern.compile("name\\s*=\"([^\"]*)\"");
        Pattern valuePattern = Pattern.compile("value\\s*=\"([^\"]*)\"");
        while (tagMatcher.find()) {
            Matcher matcher = null;
            String name = null;
            String value = null;

            String inputTag = tagMatcher.group();

            matcher = namePattern.matcher(inputTag);
            if (matcher.find()) {
                name = matcher.group(1);
            }

            matcher = valuePattern.matcher(inputTag);
            if (matcher.find()) {
                value = matcher.group(1);
            }

            if (name != null && value != null && name.equals("solution") == false) {
                values.add(new StringPart(name, value));
            }
        }
    } catch (HttpException ex) {
        logger.error("Exception when getting submit page", ex);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(ex.getMessage());
        result.setOutputText("IOException");
        return result;
    } catch (IOException ex) {
        logger.error("Exception when getting submit page", ex);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(ex.getMessage());
        result.setOutputText("IOException");
        return result;
    }

    values.add(new StringPart("task", task_id.toString()));

    String filename = properties.getProperty("CODE_FILENAME");
    filename = filename.replaceAll("\\." + properties.getProperty("CODEFILE_EXTENSION") + "$", "");
    filename = filename + "." + properties.getProperty("CODEFILE_EXTENSION");
    FilePart filePart = new FilePart("solution", new ByteArrayPartSource(filename, path.getBytes()));
    values.add(filePart);

    /* wysyanie rozwizania */
    logger.debug("Submiting solution");
    Integer solution_id = null;
    postMethod = new PostMethod("http://main.edu.pl/user.phtml?op=submit&m=db_insert&c=" + contest_id);
    postMethod.setRequestEntity(new MultipartRequestEntity(values.toArray(new Part[0]), client.getParams()));
    try {
        try {
            client.executeMethod(postMethod);
            HttpMethod method = postMethod;

            /* check if redirect */
            Header locationHeader = postMethod.getResponseHeader("location");
            if (locationHeader != null) {
                String redirectLocation = locationHeader.getValue();
                GetMethod getMethod = new GetMethod(
                        new URI(postMethod.getURI(), new URI(redirectLocation, false)).getURI());
                client.executeMethod(getMethod);
                method = getMethod;
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            Matcher matcher = Pattern.compile("<tr id=\"rptr\">.*?</tr>", Pattern.DOTALL)
                    .matcher(sb.toString());
            if (matcher.find()) {
                Matcher idMatcher = Pattern.compile("id=([0-9]+)").matcher(matcher.group());
                if (idMatcher.find()) {
                    solution_id = Integer.parseInt(idMatcher.group(1));
                }
            }
            if (solution_id == null) {
                throw new IllegalArgumentException("solution_id == null");
            }
        } catch (HttpException e) {
            new IllegalArgumentException(e);
        } catch (IOException e) {
            new IllegalArgumentException(e);
        } catch (NumberFormatException e) {
            new IllegalArgumentException(e);
        } catch (IllegalStateException e) {
            new IllegalArgumentException(e);
        }

    } catch (IllegalArgumentException e) {
        logger.error("Exception when submiting solution", e);
        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
        result.setNotes(e.getMessage());
        result.setOutputText("IllegalArgumentException");
        postMethod.releaseConnection();
        return result;
    }

    postMethod.releaseConnection();

    /* sprawdzanie statusu */
    logger.debug("Checking result for main.id=" + solution_id);
    Pattern resultRowPattern = Pattern.compile("id=" + solution_id + ".*?</tr>", Pattern.DOTALL);
    Pattern resultPattern = Pattern.compile(
            "</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?)</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?)</td>",
            Pattern.DOTALL);
    result_loop: while (true) {
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(e.getMessage());
            result.setOutputText("InterruptedException");
            return result;
        }

        GetMethod getMethod = new GetMethod("http://main.edu.pl/user.phtml?op=zgloszenia&c=" + contest_id);
        try {
            client.executeMethod(getMethod);
            String response = getMethod.getResponseBodyAsString(1024 * 1024);
            getMethod.releaseConnection();

            Matcher matcher = resultRowPattern.matcher(response);
            // "</td>.*?<td.*?>.*?[NAZWA_ZADANIA]</td>.*?<td.*?>(.*?[STATUS])</td>.*?<td.*?>.*?</td>.*?<td.*?>(.*?[PUNKTY])</td>"
            while (matcher.find()) {
                Matcher resultMatcher = resultPattern.matcher(matcher.group());

                if (resultMatcher.find() && resultMatcher.groupCount() == 2) {
                    String resultType = resultMatcher.group(1);
                    if (resultType.equals("?")) {
                        continue;
                    } else if (resultType.matches("B..d kompilacji")) { // CE
                        result.setStatus(ResultsStatusEnum.CE.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.matches("Program wyw.aszczony")) { // TLE
                        result.setStatus(ResultsStatusEnum.TLE.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.matches("B..d wykonania")) { // RTE
                        result.setStatus(ResultsStatusEnum.RE.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.matches("Z.a odpowied.")) { // WA
                        result.setStatus(ResultsStatusEnum.WA.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else if (resultType.equals("OK")) { // AC
                        result.setStatus(ResultsStatusEnum.ACC.getCode());
                        result.setPoints(
                                calculatePoints(resultMatcher.group(2), input.getMaxPoints(), max_points));
                    } else {
                        result.setStatus(ResultsStatusEnum.UNDEF.getCode());
                        result.setNotes("Unknown status: \"" + resultType + "\"");
                    }
                    break result_loop;
                }
            }
        } catch (HttpException ex) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(ex.getMessage());
            result.setOutputText("HttpException");
            return result;
        } catch (IOException ex) {
            result.setStatus(ResultsStatusEnum.UNDEF.getCode());
            result.setNotes(ex.getMessage());
            result.setOutputText("IOException");
            return result;
        }
    }
    return result;
}

From source file:slash.navigation.rest.MultipartRequest.java

protected void doExecute() throws IOException {
    if (parts.size() > 0)
        ((EntityEnclosingMethod) method).setRequestEntity(
                new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), method.getParams()));
    super.doExecute();
}

From source file:smartrics.rest.client.RestClientImpl.java

private RequestEntity configureMultipartFileUpload(HttpMethod m, final RestRequest request,
        RequestEntity requestEntity, String fileName) {
    File file = new File(fileName);
    try {/*  w w  w . j a  va 2 s  .  c o  m*/
        requestEntity = new MultipartRequestEntity(
                new Part[] { new FilePart(request.getMultipartFileParameterName(), file) },
                ((EntityEnclosingMethod) m).getParams());
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException("File not found: " + fileName, e);
    }
    return requestEntity;
}

From source file:ucar.unidata.ui.HttpFormEntry.java

private static PostMethod getMethod(List entries, String urlPath) {
    PostMethod postMethod = new PostMethod(urlPath);
    boolean anyFiles = false;
    int count = 0;
    List goodEntries = new ArrayList();
    for (int i = 0; i < entries.size(); i++) {
        HttpFormEntry formEntry = (HttpFormEntry) entries.get(i);
        if (!formEntry.okToPost()) {
            continue;
        }//from   w  w w  .  ja v  a 2s. c  o  m
        goodEntries.add(entries.get(i));
        if (formEntry.type == TYPE_FILE) {
            anyFiles = true;
        }
    }

    if (anyFiles) {
        Part[] parts = new Part[goodEntries.size()];
        for (int i = 0; i < goodEntries.size(); i++) {
            HttpFormEntry formEntry = (HttpFormEntry) goodEntries.get(i);
            if (formEntry.type == TYPE_FILE) {
                parts[i] = formEntry.getFilePart();
            } else {
                //Not sure why but we have seen a couple of times
                //the byte value '0' gets into one of these strings
                //This causes an error in the StringPart.
                //                    System.err.println("
                String value = formEntry.getValue();
                char with = new String(" ").charAt(0);
                while (value.indexOf(0) >= 0) {
                    value = value.replace((char) 0, with);
                }
                parts[i] = new StringPart(formEntry.getName(), value);
            }
        }
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
    } else {
        for (int i = 0; i < goodEntries.size(); i++) {
            HttpFormEntry formEntry = (HttpFormEntry) goodEntries.get(i);
            postMethod.addParameter(new NameValuePair(formEntry.getName(), formEntry.getValue()));
        }
    }

    return postMethod;
}

From source file:uk.ac.edukapp.servlets.pojos.Creator.java

private Widgetprofile uploadWidgetToWookie(File widgetFile, ServletContext ctx, Useraccount userAccount)
        throws JDOMException, IOException, RESTException {

    HttpClient client = new HttpClient();
    WookieServerConfiguration wookie = WookieServerConfiguration.getInstance();
    client.getState().setCredentials(wookie.getAuthScope(), wookie.getCredentials());

    PostMethod postMethod = new PostMethod(wookie.getWookieServerLocation() + "/widgets");
    FilePart filePart = new FilePart("widgetFile", widgetFile);
    Part[] parts = { filePart };//from   www . j a v a  2 s  .  c o  m
    postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

    int status = client.executeMethod(postMethod);

    if (status == 200 || status == 201) {
        boolean createOrUpdate = (status == 201) ? true : false;

        Widgetprofile widgetprofile = this.createWidgetProfileFromResponse(postMethod.getResponseBodyAsStream(),
                ctx, createOrUpdate, userAccount);
        SolrConnector.getInstance().index();
        addUserUploadActivity(widgetprofile.getId(), userAccount, ctx, createOrUpdate);

        return widgetprofile;
    } else {
        throw new RESTException("Recived status code: " + status + " from wookie!");
    }

}

From source file:xtremweb.communications.HTTPClient.java

/**
 * This uploads a data content to server
 *
 * @param command// w  w w.  j  a va 2s.  c  o m
 *            is the command to send to server
 * @param content
 *            represents a File to get data to upload
 * @since XWHEP 1.0.0
 */
@Override
public void uploadData(final XMLRPCCommandUploadData command, final File content) throws IOException {

    try {
        mileStone("<uploadData>");

        open(command.getURI());

        command.setUser(getConfig().getUser());

        mileStone("Uploading " + command.toXml());

        post = new PostMethod(httpClient.getHostConfiguration().getHostURL());
        final Part[] parts = { new StringPart(XWPostParams.XMLDESC.toString(), command.toXml()),
                new FilePart(XWPostParams.XWUPLOAD.toString(), content) };

        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        final int status = httpClient.executeMethod(post);
        if (status != HttpStatus.SC_OK) {
            throw new IOException("can't upload data status = " + status);
        }
    } catch (final Exception e) {
        mileStone("<error method='uploadData' msg='" + e.getMessage() + "' />");
        getLogger().error("Upload error " + command.getURI() + " " + e);
    } finally {
        post.releaseConnection();
        close();
        mileStone("</uploadData>");
    }
}