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.craftercms.studio.impl.v1.deployment.PreviewDeployer.java

@Override
public void deleteFile(String site, String path) {

    DeploymentEndpointConfigTO deploymentEndpointConfigTO = siteService.getPreviewDeploymentEndpoint(site);
    URL requestUrl = null;//w w  w .  ja v a  2  s .co m

    try {
        String url = DEPLOYER_SERVLET_URL;
        List<Part> formParts = new ArrayList<>();
        if (deploymentEndpointConfigTO != null) {
            requestUrl = new URL(deploymentEndpointConfigTO.getServerUrl());
            formParts.add(new StringPart(DEPLOYER_PASSWORD_PARAM, deploymentEndpointConfigTO.getPassword()));
            formParts.add(new StringPart(DEPLOYER_TARGET_PARAM, deploymentEndpointConfigTO.getTarget()));
        } else {
            requestUrl = new URL("http", defaultServer, defaultPort, url);
            formParts.add(new StringPart(DEPLOYER_PASSWORD_PARAM, defaultPassword));
            formParts.add(new StringPart(DEPLOYER_TARGET_PARAM, defaultTarget));
        }

        StringBuilder sbDeletedFiles = new StringBuilder(path);
        if (path.endsWith("/index.xml")) {
            RepositoryItem[] children = contentRepository.getContentChildren(
                    contentService.expandRelativeSitePath(site, path.replace("/index.xml", "")));
            if (!(children != null && children.length > 1)) {
                sbDeletedFiles.append(FILES_SEPARATOR).append(path.replace("/index.xml", ""));

            }
        }
        formParts.add(new StringPart(DEPLOYER_DELETED_FILES_PARAM, sbDeletedFiles.toString()));
        formParts.add(new StringPart(DEPLOYER_SITE_PARAM, site));

        PostMethod postMethod = new PostMethod(requestUrl.toString());
        postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

        Part[] parts = new Part[formParts.size()];

        for (int i = 0; i < formParts.size(); i++)
            parts[i] = formParts.get(i);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        HttpClient client = new HttpClient();
        int status = client.executeMethod(postMethod);
        postMethod.releaseConnection();
    } catch (Exception err) {
        logger.error("error while preview deploying '" + site + ":" + path + "'", err);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.PreviewDeployer.java

protected void deleteSite(String site) {

    DeploymentEndpointConfigTO deploymentEndpointConfigTO = siteService.getPreviewDeploymentEndpoint(site);
    URL requestUrl = null;// www  .  ja va 2s.  c o m

    try {
        String url = DEPLOYER_SERVLET_URL;
        List<Part> formParts = new ArrayList<>();
        if (deploymentEndpointConfigTO != null) {
            requestUrl = new URL(deploymentEndpointConfigTO.getServerUrl());
            formParts.add(new StringPart(DEPLOYER_PASSWORD_PARAM, deploymentEndpointConfigTO.getPassword()));
            formParts.add(new StringPart(DEPLOYER_TARGET_PARAM, deploymentEndpointConfigTO.getTarget()));
        } else {
            requestUrl = new URL("http", defaultServer, defaultPort, url);
            formParts.add(new StringPart(DEPLOYER_PASSWORD_PARAM, defaultPassword));
            formParts.add(new StringPart(DEPLOYER_TARGET_PARAM, defaultTarget));
        }

        StringBuilder sbDeletedFiles = new StringBuilder("/");

        formParts.add(new StringPart(DEPLOYER_DELETED_FILES_PARAM, sbDeletedFiles.toString()));
        formParts.add(new StringPart(DEPLOYER_SITE_PARAM, site));

        PostMethod postMethod = new PostMethod(requestUrl.toString());
        postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

        Part[] parts = new Part[formParts.size()];

        for (int i = 0; i < formParts.size(); i++)
            parts[i] = formParts.get(i);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        HttpClient client = new HttpClient();
        int status = client.executeMethod(postMethod);
        postMethod.releaseConnection();
    } catch (Exception err) {
        logger.error("error while deleting site from preview: '" + site + "'", err);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.SyncTargetDeployer.java

@Override
public void deployFiles(String site, List<String> paths, List<String> deletedFiles)
        throws ContentNotFoundForPublishingException, UploadFailedException {
    logger.debug("Start deploying items for site \"{0}\", target \"{1}\", number of items \"{2}\"", site,
            endpointConfig.getName(), paths.size());
    URL requestUrl = null;//from  w ww  . j a va  2  s .  com
    try {
        requestUrl = new URL(endpointConfig.getServerUrl());
    } catch (MalformedURLException e) {
        logger.error("Invalid server URL for target {0}", endpointConfig.getName());
        throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl(), e);
    }

    ByteArrayPartSource baps = null;
    PartSource metadataPart = null;
    StringPart stringPart = null;
    FilePart filePart = null;

    // TODO: implement reactor version of deployment events
    int cntFiles = 0;
    StringBuilder sbDeletedFiles = new StringBuilder();
    List<Part> formParts = new ArrayList<Part>();

    formParts.add(new StringPart(PASSWORD_REQUEST_PARAMETER, endpointConfig.getPassword()));
    formParts.add(new StringPart(TARGET_REQUEST_PARAMETER, endpointConfig.getTarget()));
    String siteId = endpointConfig.getSiteId();
    if (StringUtils.isEmpty(siteId)) {
        siteId = site;
    }
    formParts.add(new StringPart(SITE_REQUEST_PARAMETER, siteId));

    logger.debug("Preparing deployment items for target {0}", endpointConfig.getName());
    for (String path : paths) {
        logger.debug("Parsing \"{0}\" , site \"{1}\"; for publishing on target \"{2}\"", path, site,
                endpointConfig.getName());
        logger.debug("Get content for \"{0}\" , site \"{1}\", environment \"{2}\"", path, site, environment);
        File file = new File(getDestinationPath(site, path, environment));
        InputStream input = null;
        try {
            input = FileUtils.openInputStream(file);
            if (input == null || input.available() < 0) {
                if (file.exists() && !file.isDirectory()) {
                    baps = null;
                    stringPart = null;
                    filePart = null;
                    formParts = null;
                    throw new ContentNotFoundForPublishingException(site, endpointConfig.getName(), path);
                } else {
                    // Content does not exist - skip deploying file
                    continue;
                }
            }
        } catch (IOException err) {
            logger.error("Error reading input stream from envirnoment store for content at path: " + path
                    + " site: " + site + " environment: " + environment);
            if (!file.exists()) {
                logger.error("File expected, but does not exist at path: " + file.getAbsolutePath());
            }
            continue;
        }
        String fileName = file.getName();

        byte[] byteArray = null;

        try {
            byteArray = IOUtils.toByteArray(input);
        } catch (IOException e) {
            logger.error("Error while converting input stream to byte array", e);
            baps = null;
            stringPart = null;
            filePart = null;
            formParts = null;
        } finally {
            IOUtils.closeQuietly(input);
            input = null;
        }
        baps = new ByteArrayPartSource(fileName, byteArray);

        logger.debug("Create http request parameters for \"{0}\" , site \"{1}\"; publishing on target \"{2}\"",
                path, site, endpointConfig.getName());
        int idx = path.lastIndexOf("/");
        String relativePath = path.substring(0, idx + 1) + fileName;
        stringPart = new StringPart(CONTENT_LOCATION_REQUEST_PARAMETER + cntFiles, relativePath);
        formParts.add(stringPart);
        filePart = new FilePart(CONTENT_FILE_REQUEST_PARAMETER + cntFiles, baps);
        formParts.add(filePart);
        /*
        if (item.getAction() == PublishingSyncItem.Action.MOVE) {
        if (item.getOldPath() != null && !item.getOldPath().equalsIgnoreCase(item.getPath())) {
            LOGGER.debug("Add old path to be deleted for MOVE action (\"{0}\")", item.getOldPath());
            eventItem.setOldPath(item.getOldPath());
            if (sbDeletedFiles.length() > 0) {
                sbDeletedFiles.append(",").append(item.getOldPath());
            } else {
                sbDeletedFiles.append(item.getOldPath());
            }
            if (item.getOldPath().endsWith("/" + _indexFile)) {
                sbDeletedFiles.append(FILES_SEPARATOR).append(item.getOldPath().replace("/" + _indexFile, ""));
            }
        }
        }*/
        cntFiles++;

        // TODO: implement metadata transfer
    }

    for (int i = 0; i < deletedFiles.size(); i++) {
        if (i > 0) {
            sbDeletedFiles.append(FILES_SEPARATOR);
        }
        sbDeletedFiles.append(deletedFiles.get(i));
    }

    if (sbDeletedFiles.length() > 0) {
        formParts.add(new StringPart(DELETED_FILES_REQUEST_PARAMETER, sbDeletedFiles.toString()));
    }
    logger.debug("Create http request to deploy content for target {0} ({1})", endpointConfig.getName(),
            endpointConfig.getTarget());
    PostMethod postMethod = null;
    HttpClient client = null;
    try {
        logger.debug("Create HTTP Post Method");
        postMethod = new PostMethod(requestUrl.toString());
        postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        Part[] parts = new Part[formParts.size()];
        for (int i = 0; i < formParts.size(); i++)
            parts[i] = formParts.get(i);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        client = new HttpClient();

        logger.debug("Execute HTTP POST request \"{0}\"", postMethod.getURI());
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
            logger.info("Successfully deployed on target {0}", endpointConfig.getName());
        } else {
            logger.error("Deployment failed for on target {1}. Deployment agent returned status {2}",
                    endpointConfig.getName(), HttpStatus.getStatusText(status));
            throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl());
        }
    } catch (HttpException e) {
        logger.error("Publish failed for target {0} due to http protocol exception", endpointConfig.getName());
        throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl(), e);
    } catch (IOException e) {
        logger.error("Publish failed for target {0} due to I/O (transport) exception",
                endpointConfig.getName());
        throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl(), e);
    } finally {
        logger.debug("Release http connection and release resources");
        if (client != null) {
            HttpConnectionManager mgr = client.getHttpConnectionManager();
            if (mgr instanceof SimpleHttpConnectionManager) {
                ((SimpleHttpConnectionManager) mgr).shutdown();
            }
        }
        if (postMethod != null) {
            postMethod.releaseConnection();
            postMethod = null;
            client = null;
        }
        baps = null;
        stringPart = null;
        filePart = null;
        formParts = null;
    }

    //LOGGER.debug("Publishing deployment event for target \"{0}\" with \"{1}\" items.", target.getName(), 0/*eventItems.size()*/);
    //contentRepository.publishDeployEvent(target.getName(), eventItems);

    logger.info("Deployment successful on target {0}", endpointConfig.getName());
    logger.debug("Finished deploying items for site \"{0}\", target \"{1}\", number of items \"{2}\"", site,
            endpointConfig.getName(), paths.size());
}

From source file:org.craftercms.studio.impl.v1.repository.alfresco.AlfrescoContentRepository.java

/**
 * create a multipart post request and fire to Alfresco
 *
 * @param uri//from   w  w  w  . j  av  a2 s .  co m
 *          the target service URI
 * @param params
 *          request parameters
 * @param body
 *          post data
 * @param bodyMimeType
 *          post data mime type
 * @param charSet
 *          post data char set
 * @return response body
 * @throws Exception
 */
protected String alfrescoMultipartPostRequest(String uri, Map<String, String> params, InputStream body,
        String bodyMimeType, String charSet) throws Exception {
    long startTime = System.currentTimeMillis();
    String serviceURL = buildAlfrescoRequestURL(uri, new HashMap<String, String>(0));
    PostMethod postMethod = new PostMethod(serviceURL);
    // create multipart request parts
    int partSize = params.size() + 1;
    Part[] parts = new Part[partSize];
    int index = 0;
    for (String key : params.keySet()) {
        parts[index] = new StringPart(key, params.get(key));
        index++;
    }
    byte[] bytes = IOUtils.toByteArray(body);
    String name = params.get("filename");
    PartSource partSource = new ByteArrayPartSource(name, bytes);
    parts[index] = new FilePart("filedata", partSource, bodyMimeType, charSet);

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

    // connect to alfresco and get response
    HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    logger.debug("Executing multipart post request to " + uri);
    int status = httpClient.executeMethod(postMethod);
    logger.debug("Response status back from the server: " + status);

    long duration = System.currentTimeMillis() - startTime;
    logger.debug(
            "TRACE: alfrescoMultipartPostRequest(String uri, Map<String, String> params, InputStream body, String bodyMimeType, String charSet); {0}, {1}, {2}, {3}, {4}\n\t\tDuration: {5}",
            uri, params, "body", bodyMimeType, charSet, duration);
    return postMethod.getResponseBodyAsString();
}

From source file:org.dataconservancy.dcs.ingest.ui.server.FileUploadServlet.java

private void uploadfile(String depositurl, String filename, InputStream is, HttpServletResponse resp)
        throws IOException {
    File tmp = null;/*  w w w. jav  a  2s .  c o  m*/
    FileOutputStream fos = null;
    PostMethod post = null;

    //System.out.println(filename + " -> " + depositurl);

    try {
        tmp = File.createTempFile("fileupload", null);
        fos = new FileOutputStream(tmp);
        FileUtil.copy(is, fos);

        HttpClient client = new HttpClient();

        post = new PostMethod(depositurl);

        Part[] parts = { new FilePart(filename, tmp) };

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

        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_ACCEPTED || status == HttpStatus.SC_CREATED) {
            resp.setStatus(status);

            String src = post.getResponseHeader("X-dcs-src").getValue();
            String atomurl = post.getResponseHeader("Location").getValue();

            resp.setContentType("text/html");
            resp.getWriter().print("<html><body><p>^" + src + "^" + atomurl + "^</p></body></html>");
            resp.flushBuffer();
        } else {
            resp.sendError(status, post.getStatusText());
            return;
        }
    } finally {
        if (tmp != null) {
            tmp.delete();
        }

        if (is != null) {
            is.close();
        }

        if (fos != null) {
            fos.close();
        }

        if (post != null) {
            post.releaseConnection();
        }
    }
}

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

/**
 * This method does the heavy lifting when it comes to downloads.
 * /* w w  w  .  ja  v  a 2s  . c  o  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()));

    // 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:org.dbpedia.spotlight.evaluation.external.ExtractivClient.java

/**
 * Adapted from// ww  w. j  a v a  2s .  c  om
 *
 * https://github.com/extractiv/ExtractivPublicCode/blob/master/src/main/java/com/extractiv/rest/RESTDemo.java
 *
 *
 * Generates a HttpMethodBase that will request the given file to be processed by the Extractiv annotation service.
 *
 * @param extractivURI The URI of the Extractiv annotation service
 * @param file       The file to process
 */
private PostMethod getExtractivProcessFileRequest(final URI extractivURI, final File file)
        throws FileNotFoundException {

    final PartBase filePart = new FilePart("content", file, "multipart/form-data", null);

    // bytes to upload
    final ArrayList<Part> message = new ArrayList<Part>();
    message.add(filePart);
    message.add(new StringPart("formids", "content"));
    message.add(new StringPart("output_format", "JSON"));
    if (apiKey != null) {
        message.add(new StringPart("api_key", apiKey));
    }

    final Part[] messageArray = message.toArray(new Part[0]);

    // Use a Post for the file upload
    final PostMethod postMethod = new PostMethod(extractivURI.toString());
    postMethod.setRequestEntity(new MultipartRequestEntity(messageArray, postMethod.getParams()));

    return postMethod;

}

From source file:org.eclipse.ecf.internal.bulletinboard.commons.webapp.MultipartRequest.java

/**
 * TODO: make sure we are using the MultipartRequestEntity in the correct
 * manner. The deprecated MultipartPostMethod was very different.
 * @throws IOException /*from www  .  j a  v a2  s  .c om*/
 */
@Override
public void execute() throws IOException {
    ((PostMethod) method).setRequestEntity(
            new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), method.getParams()));
    super.execute();
}

From source file:org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java

public void postAttachment(String bugReportID, String comment, AbstractTaskAttachmentSource source,
        TaskAttribute attachmentAttribute, IProgressMonitor monitor)
        throws HttpException, IOException, CoreException {
    monitor = Policy.monitorFor(monitor);
    String description = source.getDescription();
    String contentType = source.getContentType();
    String filename = source.getName();
    boolean isPatch = false;

    if (attachmentAttribute != null) {
        TaskAttachmentMapper mapper = TaskAttachmentMapper.createFrom(attachmentAttribute);

        if (mapper.getDescription() != null) {
            description = mapper.getDescription();
        }//from  w w w .ja  v a2s  .  c o m

        if (mapper.getContentType() != null) {
            contentType = mapper.getContentType();
        }

        if (mapper.getFileName() != null) {
            filename = mapper.getFileName();
        }

        if (mapper.isPatch() != null) {
            isPatch = mapper.isPatch();
        }
    }
    Assert.isNotNull(bugReportID);
    Assert.isNotNull(source);
    Assert.isNotNull(contentType);
    if (description == null) {
        throw new CoreException(new Status(IStatus.WARNING, BugzillaCorePlugin.ID_PLUGIN,
                Messages.BugzillaClient_description_required_when_submitting_attachments));
    }

    hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
    authenticate(monitor);
    GzipPostMethod postMethod = null;

    try {
        postMethod = new GzipPostMethod(
                WebUtil.getRequestPath(repositoryUrl + IBugzillaConstants.URL_POST_ATTACHMENT_UPLOAD), true);
        // This option causes the client to first
        // check
        // with the server to see if it will in fact receive the post before
        // actually sending the contents.
        postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        List<PartBase> parts = new ArrayList<PartBase>();
        parts.add(new StringPart(IBugzillaConstants.POST_INPUT_ACTION, VALUE_ACTION_INSERT,
                getCharacterEncoding()));

        parts.add(new StringPart(IBugzillaConstants.POST_INPUT_BUGID, bugReportID, getCharacterEncoding()));
        if (description != null) {
            parts.add(new StringPart(IBugzillaConstants.POST_INPUT_DESCRIPTION, description,
                    getCharacterEncoding()));
        }
        if (comment != null) {
            parts.add(new StringPart(IBugzillaConstants.POST_INPUT_COMMENT, comment, getCharacterEncoding()));
        }
        parts.add(new BugzillaFilePart(source, filename, contentType, getCharacterEncoding()));

        if (isPatch) {
            parts.add(new StringPart(ATTRIBUTE_ISPATCH, VALUE_ISPATCH));
        } else {
            parts.add(new StringPart(ATTRIBUTE_CONTENTTYPEMETHOD, VALUE_CONTENTTYPEMETHOD_MANUAL));
            parts.add(new StringPart(ATTRIBUTE_CONTENTTYPEENTRY, contentType));
        }
        if (attachmentAttribute != null) {
            Collection<TaskAttribute> attributes = attachmentAttribute.getAttributes().values();
            Iterator<TaskAttribute> itr = attributes.iterator();
            while (itr.hasNext()) {
                TaskAttribute a = itr.next();
                if (a.getId().startsWith(BugzillaAttribute.KIND_FLAG_TYPE) && repositoryConfiguration != null) {
                    List<BugzillaFlag> flags = repositoryConfiguration.getFlags();
                    TaskAttribute requestee = a.getAttribute("requestee"); //$NON-NLS-1$
                    a = a.getAttribute("state"); //$NON-NLS-1$
                    String value = a.getValue();
                    String id = ""; //$NON-NLS-1$
                    if (value.equals(" ")) { //$NON-NLS-1$
                        continue;
                    }
                    String flagname = a.getMetaData().getLabel();
                    BugzillaFlag theFlag = null;
                    for (BugzillaFlag bugzillaFlag : flags) {
                        if (flagname.equals(bugzillaFlag.getName())) {
                            theFlag = bugzillaFlag;
                            break;
                        }
                    }
                    if (theFlag != null) {
                        int flagTypeNumber = theFlag.getFlagId();
                        id = "flag_type-" + flagTypeNumber; //$NON-NLS-1$
                        value = a.getValue();
                        if (value.equals("?") && requestee != null) { //$NON-NLS-1$
                            parts.add(new StringPart("requestee_type-" + flagTypeNumber, //$NON-NLS-1$
                                    requestee.getValue() != null ? requestee.getValue() : "")); //$NON-NLS-1$
                        }
                    }
                    parts.add(new StringPart(id, value != null ? value : "")); //$NON-NLS-1$
                } else if (a.getId().startsWith(BugzillaAttribute.KIND_FLAG)) {
                    TaskAttribute flagnumber = a.getAttribute("number"); //$NON-NLS-1$
                    TaskAttribute requestee = a.getAttribute("requestee"); //$NON-NLS-1$
                    a = a.getAttribute("state"); //$NON-NLS-1$
                    String id = "flag-" + flagnumber.getValue(); //$NON-NLS-1$
                    String value = a.getValue();
                    if (value.equals(" ") || value.equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
                        value = "X"; //$NON-NLS-1$
                    }
                    if (value.equals("?") && requestee != null) { //$NON-NLS-1$
                        parts.add(new StringPart("requestee-" + flagnumber.getValue(), //$NON-NLS-1$
                                requestee.getValue() != null ? requestee.getValue() : "")); //$NON-NLS-1$
                    }
                    parts.add(new StringPart(id, value != null ? value : "")); //$NON-NLS-1$
                }
            }
        }
        String token = null;
        BugzillaVersion bugzillaVersion = null;
        if (repositoryConfiguration != null) {
            bugzillaVersion = repositoryConfiguration.getInstallVersion();
        } else {
            bugzillaVersion = BugzillaVersion.MIN_VERSION;
        }
        if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_4_0) > 0) {
            token = getTokenInternal(repositoryUrl + ENTER_ATTACHMENT_CGI + bugReportID, monitor);
        }
        if (token != null) {
            parts.add(new StringPart(BugzillaAttribute.TOKEN.getKey(), token));
        }

        postMethod.setRequestEntity(
                new MultipartRequestEntity(parts.toArray(new Part[1]), postMethod.getParams()));
        postMethod.setDoAuthentication(true);
        int status = WebUtil.execute(httpClient, hostConfiguration, postMethod, monitor);
        if (status == HttpStatus.SC_OK) {
            InputStream input = getResponseStream(postMethod, monitor);
            try {
                parsePostResponse(bugReportID, input);
            } finally {
                input.close();
            }

        } else {
            WebUtil.releaseConnection(postMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, repositoryUrl.toString(), "Http error: " //$NON-NLS-1$
                            + HttpStatus.getStatusText(status)));
            // throw new IOException("Communication error occurred during
            // upload. \n\n"
            // + HttpStatus.getStatusText(status));
        }
    } finally {
        if (postMethod != null) {
            WebUtil.releaseConnection(postMethod, monitor);
        }
    }
}

From source file:org.eclipse.mylyn.internal.jira.core.service.web.JiraWebClient.java

public void attachFile(final JiraIssue issue, final String comment, final FilePart filePart,
        final String contentType, IProgressMonitor monitor) throws JiraException {
    doInSession(monitor, new JiraWebSessionCallback() {
        @Override/*from  www. j  a v a 2  s.  c  o  m*/
        public void run(JiraClient server, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder attachFileURLBuffer = new StringBuilder(baseUrl);
            attachFileURLBuffer.append("/secure/AttachFile.jspa"); //$NON-NLS-1$

            PostMethod post = new PostMethod(attachFileURLBuffer.toString());

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

            StringPart idPart = new StringPart("id", issue.getId()); //$NON-NLS-1$
            StringPart commentLevelPart = new StringPart("commentLevel", ""); //$NON-NLS-1$ //$NON-NLS-2$

            // The transfer encodings have to be removed for some reason
            // There is no need to send the content types for the strings,
            // as they should be in the correct format
            idPart.setTransferEncoding(null);
            idPart.setContentType(null);

            if (comment != null) {
                StringPart commentPart = new StringPart("comment", comment); //$NON-NLS-1$
                commentPart.setTransferEncoding(null);
                commentPart.setContentType(null);
                parts.add(commentPart);
            }

            commentLevelPart.setTransferEncoding(null);
            commentLevelPart.setContentType(null);

            filePart.setTransferEncoding(null);
            if (contentType != null) {
                filePart.setContentType(contentType);
            }
            parts.add(filePart);
            parts.add(idPart);
            parts.add(commentLevelPart);

            post.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams()));

            try {
                execute(post);
                if (!expectRedirect(post, "/secure/ManageAttachments.jspa?id=" + issue.getId())) { //$NON-NLS-1$
                    handleErrorMessage(post);
                }
            } finally {
                post.releaseConnection();
            }
        }
    });
}