Example usage for org.apache.http.entity.mime MultipartEntity MultipartEntity

List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity

Introduction

In this page you can find the example usage for org.apache.http.entity.mime MultipartEntity MultipartEntity.

Prototype

public MultipartEntity() 

Source Link

Usage

From source file:org.bimserver.client.Channel.java

public long checkin(String baseAddress, String token, long poid, String comment, long deserializerOid,
        boolean merge, boolean sync, long fileSize, String filename, InputStream inputStream)
        throws ServerException, UserException {
    String address = baseAddress + "/upload";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }//from  w w  w  .ja  va  2 s.c  o m
        }
    });

    httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                        if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    HttpPost httppost = new HttpPost(address);
    try {
        // TODO find some GzipInputStream variant that _compresses_ instead of _decompresses_ using deflate for now
        InputStreamBody data = new InputStreamBody(new DeflaterInputStream(inputStream), filename);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("data", data);
        reqEntity.addPart("token", new StringBody(token));
        reqEntity.addPart("deserializerOid", new StringBody("" + deserializerOid));
        reqEntity.addPart("merge", new StringBody("" + merge));
        reqEntity.addPart("poid", new StringBody("" + poid));
        reqEntity.addPart("comment", new StringBody("" + comment));
        reqEntity.addPart("sync", new StringBody("" + sync));
        reqEntity.addPart("compression", new StringBody("deflate"));
        httppost.setEntity(reqEntity);

        HttpResponse httpResponse = httpclient.execute(httppost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            JsonParser jsonParser = new JsonParser();
            JsonElement result = jsonParser
                    .parse(new JsonReader(new InputStreamReader(httpResponse.getEntity().getContent())));
            if (result instanceof JsonObject) {
                JsonObject jsonObject = (JsonObject) result;
                if (jsonObject.has("exception")) {
                    JsonObject exceptionJson = jsonObject.get("exception").getAsJsonObject();
                    String exceptionType = exceptionJson.get("__type").getAsString();
                    String message = exceptionJson.has("message") ? exceptionJson.get("message").getAsString()
                            : "unknown";
                    if (exceptionType.equals(UserException.class.getSimpleName())) {
                        throw new UserException(message);
                    } else if (exceptionType.equals(ServerException.class.getSimpleName())) {
                        throw new ServerException(message);
                    }
                } else {
                    return jsonObject.get("checkinid").getAsLong();
                }
            }
        }
    } catch (ClientProtocolException e) {
        LOGGER.error("", e);
    } catch (IOException e) {
        LOGGER.error("", e);
    }
    return -1;
}

From source file:org.jutge.joc.porra.service.EmailService.java

/**
 * Mighty delicate a process it is to send an email through the Raco webmail frontend. Let me break it down:
 * You need to log in as you'd normally do in the Raco. After a couple of redirects to the CAS server, you should be inside.
 * Then you issue a GET for the mail compose form. The response contains a form token to be used in the actual multipart POST that should send the mail.
 * The minute they change the login system or the webmail styles, this'll probably break down LOL: Let's hope they keep it this way til the Joc d'EDA is over
 * @param userAccount user to send the mail to
 * @param message the message body//from   w  w  w .j a  va  2  s .c  om
 * @throws Exception should anything crash
 */
private void sendMail(final Account userAccount, final String message) throws Exception {
    // Enviar mail pel Raco
    // Authenticate
    final List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("service", "https://raco.fib.upc.edu/oauth/gestio-api/api.jsp"));
    params.add(new BasicNameValuePair("loginDirecte", "true"));
    params.add(new BasicNameValuePair("username", "XXXXXXXX"));
    params.add(new BasicNameValuePair("password", "XXXXXXXX"));
    HttpPost post = new HttpPost("https://raco.fib.upc.edu/cas/login");
    post.setEntity(new UrlEncodedFormEntity(params));
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
        public boolean isRedirected(final HttpRequest request, final HttpResponse response,
                final HttpContext context) {
            boolean isRedirect = false;
            try {
                isRedirect = super.isRedirected(request, response, context);
            } catch (ProtocolException e) {
                EmailService.this.logger.error(e.getMessage());
            }
            if (!isRedirect) {
                final int responseCode = response.getStatusLine().getStatusCode();
                isRedirect = responseCode == 301 || responseCode == 302;
            }
            return isRedirect;
        }
    });
    HttpResponse response = httpClient.execute(post);
    HttpEntity entity = response.getEntity();
    EntityUtils.consumeQuietly(entity);
    // get form page
    final HttpGet get = new HttpGet("https://webmail.fib.upc.es/horde/imp/compose.php?thismailbox=INBOX&uniq="
            + System.currentTimeMillis());
    response = httpClient.execute(get);
    entity = response.getEntity();
    String responseBody = EntityUtils.toString(entity);
    // Find form action with uniq parameter 
    Pattern pattern = Pattern.compile(RacoUtils.RACO_MAIL_ACTION_PATTERN);
    Matcher matcher = pattern.matcher(responseBody);
    matcher.find();
    final String action = matcher.group();
    // formtoken
    responseBody = responseBody.substring(matcher.end(), responseBody.length());
    pattern = Pattern.compile(RacoUtils.RACO_FORMTOKEN_PATTERN);
    matcher = pattern.matcher(responseBody);
    matcher.find();
    String formToken = matcher.group();
    formToken = formToken.substring(28, formToken.length());
    // to
    final String email = userAccount.getEmail();
    // Send mail - it's a multipart post
    final MultipartEntity multipart = new MultipartEntity();
    multipart.addPart("MAX_FILE_SIZE", new StringBody("1038090240"));
    multipart.addPart("actionID", new StringBody("send_message"));
    multipart.addPart("__formToken_compose", new StringBody(formToken));
    multipart.addPart("messageCache", new StringBody(""));
    multipart.addPart("spellcheck", new StringBody(""));
    multipart.addPart("page", new StringBody(""));
    multipart.addPart("start", new StringBody(""));
    multipart.addPart("thismailbox", new StringBody("INBOX"));
    multipart.addPart("attachmentAction", new StringBody(""));
    multipart.addPart("reloaded", new StringBody("1"));
    multipart.addPart("oldrtemode", new StringBody(""));
    multipart.addPart("rtemode", new StringBody("1"));
    multipart.addPart("last_identity", new StringBody("0"));
    multipart.addPart("from", new StringBody("porra-joc-eda@est.fib.upc.edu"));
    multipart.addPart("to", new StringBody(email));
    multipart.addPart("cc", new StringBody(""));
    multipart.addPart("bcc", new StringBody(""));
    multipart.addPart("subject", new StringBody("Activacio Porra Joc EDA"));
    multipart.addPart("charset", new StringBody("UTF-8"));
    multipart.addPart("save_sent_mail", new StringBody("on"));
    multipart.addPart("message", new StringBody(message));
    multipart.addPart("upload_1", new StringBody(""));
    multipart.addPart("upload_disposition_1", new StringBody("attachment"));
    multipart.addPart("save_attachments_select", new StringBody("0"));
    multipart.addPart("link_attachments", new StringBody("0"));
    post = new HttpPost("https://webmail.fib.upc.es/horde/imp/" + action);
    post.setEntity(multipart);
    response = httpClient.execute(post);
    EntityUtils.consumeQuietly(entity);
    this.logger.info("EmailService.sendMail done");
}

From source file:org.oscarehr.common.service.E2ESchedulerJob.java

@Override
public void run() {
    DemographicDao demographicDao = SpringUtils.getBean(DemographicDao.class);
    OscarLogDao oscarLogDao = SpringUtils.getBean(OscarLogDao.class);
    StringBuilder sb = new StringBuilder(255);
    int success = 0;
    int failure = 0;
    int skipped = 0;
    int diffDays = 14;
    List<Integer> ids = null;

    try {/*from   www  . ja va2 s.  c  om*/
        // Gather demographic numbers for specified mode of operation
        if (diffMode) {
            if (e2eDiffDays != null && StringUtils.isNumeric(e2eDiffDays)) {
                diffDays = Integer.parseInt(e2eDiffDays);
            }

            Calendar cal = GregorianCalendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, -diffDays);
            ids = oscarLogDao.getDemographicIdsOpenedSinceTime(cal.getTime());
        } else {
            ids = demographicDao.getActiveDemographicIds();
        }
        if (ids != null)
            Collections.sort(ids);

        // Log Start Header
        StringBuilder sbStart = reuseStringBuilder(sb);
        sbStart.append("Starting E2E export job\nE2E Target URL: ").append(e2eUrl);
        if (diffMode) {
            sbStart.append("\nExport Mode: Differential - Days: ").append(diffDays);
        } else {
            sbStart.append("\nExport Mode: Full");
        }
        logger.info(sbStart.toString());
        StringBuilder sbStartRec = reuseStringBuilder(sb);
        sbStartRec.append(ids.size()).append(" records pending");
        if (ids.size() > 0) {
            sbStartRec.append("\nRange: ").append(ids.get(0)).append(" - ").append(ids.get(ids.size() - 1));
            sbStartRec.append(", Median: ").append(ids.get((ids.size() - 1) / 2));
        }
        logger.info(sbStartRec.toString());

        long startJob = System.currentTimeMillis();
        long endJob = startJob;

        for (Integer id : ids) {
            // Select Template
            E2EVelocityTemplate t = new E2EVelocityTemplate();

            // Create and load Patient data
            long startLoad = System.currentTimeMillis();
            E2EPatientExport patient = new E2EPatientExport();
            patient.setExAllTrue();
            long endLoad = startLoad;

            long startTemplate = 0;
            long endTemplate = startTemplate;
            // Load patient data and merge to template
            String output = "";
            if (patient.loadPatient(id.toString())) {
                endLoad = System.currentTimeMillis();
                if (patient.isActive()) {
                    startTemplate = System.currentTimeMillis();
                    output = t.export(patient);
                    endTemplate = System.currentTimeMillis();
                } else {
                    logger.info("[Demo: ".concat(id.toString()).concat("] Not active - skipped"));
                    skipped++;
                    continue;
                }
            } else {
                endLoad = System.currentTimeMillis();
                logger.error("[Demo: ".concat(id.toString()).concat("] Failed to load"));
                failure++;
                continue;
            }

            long startPost = System.currentTimeMillis();
            long endPost = startPost;

            // Attempt to perform HTTP POST request
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(e2eUrl);

                // Assemble Multi-part Request
                StringBuilder sbFile = reuseStringBuilder(sb);
                sbFile.append("output_").append(id).append(".xml");
                ByteArrayBody body = new ByteArrayBody(output.getBytes(), "text/xml", sbFile.toString());
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("content", body);
                httpPost.setEntity(reqEntity);

                // Send HTTP POST request
                HttpResponse response = httpclient.execute(httpPost);
                if (response != null && response.getStatusLine().getStatusCode() == 201) {
                    success++;
                } else {
                    logger.warn(response.getStatusLine());
                    failure++;
                }
            } catch (HttpHostConnectException e) {
                logger.error("Connection to ".concat(e2eUrl).concat(" refused"));
                failure++;
            } catch (NoRouteToHostException e) {
                logger.error("Can't resolve route to ".concat(e2eUrl));
                failure++;
            } catch (Exception e) {
                logger.error("Error", e);
                failure++;
            } finally {
                endPost = System.currentTimeMillis();
            }

            // Log Record completion + benchmarks
            StringBuilder sbTimer = reuseStringBuilder(sb);
            sbTimer.append("[Demo: ").append(id);
            sbTimer.append("] L:").append((endLoad - startLoad) / 1000.0);
            sbTimer.append(" T:").append((endTemplate - startTemplate) / 1000.0);
            sbTimer.append(" P:").append((endPost - startPost) / 1000.0);
            logger.info(sbTimer.toString());
        }

        endJob = System.currentTimeMillis();
        logger.info("Done E2E export job (" + convertTime(endJob - startJob) + ")");
    } catch (Throwable e) {
        logger.error("Error", e);
        logger.info("E2E export job aborted");
    } finally {
        // Log final record counts
        int unaccounted = ids.size() - success - failure - skipped;
        sb = reuseStringBuilder(sb);
        sb.append(success).append(" records processed");
        if (failure > 0)
            sb.append("\n").append(failure).append(" records failed");
        if (skipped > 0)
            sb.append("\n").append(skipped).append(" records skipped");
        if (unaccounted > 0)
            sb.append("\n").append(unaccounted).append(" records unaccounted");
        logger.info(sb.toString());
        DbConnectionFilter.releaseAllThreadDbResources();
    }
}

From source file:org.apache.sling.testing.tools.osgi.WebconsoleClient.java

/** Start specified bundle */
public void startBundle(String symbolicName) throws Exception {
    // To start the bundle we POST action=start to its URL
    final String path = getBundlePath(symbolicName, null);
    log.info("Starting bundle {} via {}", symbolicName, path);

    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("action", new StringBody("start"));
    executor.execute(builder.buildPostRequest(path).withCredentials(username, password).withEntity(entity))
            .assertStatus(200);//from w w  w .j  a va  2  s.com
}

From source file:pl.llp.aircasting.util.http.HttpBuilder.java

private HttpEntity prepareMultipart() throws UnsupportedEncodingException {
    MultipartEntity result = new MultipartEntity();

    for (Parameter parameter : parameters) {
        result.addPart(parameter.getKey(), parameter.toBody());
    }//from w  ww .j  a  v  a2s  .  c om

    return result;
}

From source file:com.parworks.androidlibrary.utils.HttpUtils.java

/**
 * Synchronous HTTP post to the specified url. Set's apikey, salt, and signature as headers.
 * @param apiKey/*from   w w w. j av a2  s  .co  m*/
 * @param salt
 * @param signature
 * @param url absolute url to endpoing
 * @param queryString
 * @return the HTTP response
 */

public HttpResponse doPost(String url, Map<String, String> queryString) {
    return doPost(url, new MultipartEntity(), queryString);
}

From source file:org.opentraces.metatracker.net.OpenTracesClient.java

public void uploadFile(String fileName) {
    try {/*from  w w  w.  j  a  v  a  2 s  .co  m*/
        DefaultHttpClient httpclient = new DefaultHttpClient();
        File f = new File(fileName);

        HttpPost httpost = new HttpPost("http://local.geotracing.com/tland/media.srv");
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("myIdentifier", new StringBody("somevalue"));
        entity.addPart("myFile", new FileBody(f));
        httpost.setEntity(entity);

        HttpResponse response;

        response = httpclient.execute(httpost);

        Log.d(LOG_TAG, "Upload result: " + response.getStatusLine());

        if (entity != null) {
            entity.consumeContent();
        }

        httpclient.getConnectionManager().shutdown();

    } catch (Throwable ex) {
        Log.d(LOG_TAG, "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace());
    }

}

From source file:org.ubicompforall.BusTUC.Speech.HTTP.java

public DummyObj sendPost(String filePath, Context context, double lat, double lon) {
    String response = "Fant ikke noe";
    long first = System.nanoTime();
    Calc calc = new Calc();
    DummyObj dummy = new DummyObj();
    HttpClient httpclient = new DefaultHttpClient();
    long second = System.nanoTime() - first;
    //   File file = new File(Environment.getExternalStorageDirectory(),
    //      filePath);
    File file = new File(filePath);
    HttpPost httppost = new HttpPost("http://vm-6114.idi.ntnu.no:1337/SpeechServer/sst");
    final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String t_id = tm.getDeviceId();
    String tmp = "TABuss";
    String p_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

    try {/*  w ww. jav  a  2s  .  c  o m*/
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("lat", new StringBody(String.valueOf(lat)));
        entity.addPart("lon", new StringBody(String.valueOf(lon)));
        entity.addPart("devID", new StringBody(tmp + p_id));
        entity.addPart("speechinput", new FileBody(file, "multipart/form-data;charset=\"UTF-8\""));

        httppost.setEntity(entity);
        response = EntityUtils.toString(httpclient.execute(httppost).getEntity(), "UTF-8");
        System.out.println("RESPONSE: " + response);
        dummy = calc.parse(response);
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }
    return dummy;

}

From source file:net.rcarz.jiraclient.RestClient.java

private JSON request(HttpEntityEnclosingRequestBase req, Issue.NewAttachment... attachments)
        throws RestException, IOException {
    if (attachments != null) {
        req.setHeader("X-Atlassian-Token", "nocheck");
        MultipartEntity ent = new MultipartEntity();
        for (Issue.NewAttachment attachment : attachments) {
            String filename = attachment.getFilename();
            Object content = attachment.getContent();
            if (content instanceof byte[]) {
                ent.addPart("file", new ByteArrayBody((byte[]) content, filename));
            } else if (content instanceof InputStream) {
                ent.addPart("file", new InputStreamBody((InputStream) content, filename));
            } else if (content instanceof File) {
                ent.addPart("file", new FileBody((File) content, filename));
            } else if (content == null) {
                throw new IllegalArgumentException("Missing content for the file " + filename);
            } else {
                throw new IllegalArgumentException(
                        "Expected file type byte[], java.io.InputStream or java.io.File but provided "
                                + content.getClass().getName() + " for the file " + filename);
            }//from   www  . j av a  2  s  .  com
        }
        req.setEntity(ent);
    }
    return request(req);
}

From source file:pl.psnc.synat.wrdz.zmkd.invocation.RestServiceCallerUtils.java

/**
 * Constructs application/form-data entity based upon the specified parameters.
 * /*from   w ww. ja  v a2  s. c o  m*/
 * @param formParams
 *            form parameters
 * @return request application/form-data entity for the service
 */
private static HttpEntity constructFormDataEntity(List<ExecutionFormParam> formParams) {
    MultipartEntity entity = new MultipartEntity();
    try {
        for (ExecutionFormParam formParam : formParams) {
            if (formParam.getValues() != null) {
                for (String value : formParam.getValues()) {
                    entity.addPart(formParam.getName(), new StringBody(value, Consts.UTF_8));
                }
            } else if (formParam.getFiles() != null) {
                for (FileValue fileValue : formParam.getFiles()) {
                    FileBody fileBody = new FileBody(fileValue.getFile(), fileValue.getFilename(),
                            fileValue.getMimetype(), null);
                    entity.addPart(formParam.getName(), fileBody);
                }
            } else {
                entity.addPart(formParam.getName(), new StringBody("", Consts.UTF_8));
            }
        }
    } catch (UnsupportedEncodingException e) {
        throw new WrdzRuntimeException("The encoding " + Consts.UTF_8 + " is not supported");
    }
    return entity;
}