Example usage for org.apache.http.entity.mime HttpMultipartMode STRICT

List of usage examples for org.apache.http.entity.mime HttpMultipartMode STRICT

Introduction

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

Prototype

HttpMultipartMode STRICT

To view the source code for org.apache.http.entity.mime HttpMultipartMode STRICT.

Click Source Link

Usage

From source file:de.xwic.appkit.core.file.impl.hbn.RemoteFileAccessClient.java

@Override
protected int storeFile(final File file) throws IOException {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart(PARAM_ACTION, new StringBody(ACTION_FILE_HANDLE));
    multipartEntity.addPart(PARAM_FH_ACTION, new StringBody(PARAM_FH_ACTION_UPLOAD));
    multipartEntity.addPart(PARAM_FH_STREAM, new FileBody(file));
    return URemoteAccessClient.multipartRequestInt(multipartEntity, config);
}

From source file:org.apache.abdera2.protocol.client.MultipartRelatedEntity.java

public MultipartRelatedEntity(Entry entry, ContentBody other, String contentType, String boundary) {
    if (entry == null || other == null)
        throw new IllegalArgumentException();
    this.boundary = boundary != null ? boundary : String.valueOf(System.currentTimeMillis());
    this.contentType = new BasicHeader("Content-Type", String.format(
            "Multipart/Related; boundary=\"%s\";type=\"%s\"", this.boundary, Helper.getMimeType(entry)));
    String cs = entry.getDocument().getCharset();
    Charset charset = cs != null ? Charset.forName(cs) : Charset.defaultCharset();
    multipart = new HttpMultipart("related", charset, this.boundary, HttpMultipartMode.STRICT);
    multipart.addBodyPart(new FormBodyPart("entry", new AbderaBody(entry)));
    String contentId = entry.getContentSrc().toString();
    if (!contentId.matches("cid\\:.+")) {
        throw new IllegalArgumentException("entry content source is not a correct content-ID");
    }//from w  w  w  . j  av  a2s  .com
    FormBodyPart other_part = new FormBodyPart("other", other);
    other_part.addField("Content-ID", String.format("<%s>", contentId.substring(4)));
    other_part.addField("Content-Type", other.getMimeType());
    multipart.addBodyPart(other_part);
}

From source file:com.app.precared.utils.MultipartEntityBuilder.java

public MultipartEntityBuilder setStrictMode() {
    this.mode = HttpMultipartMode.STRICT;
    return this;
}

From source file:org.apache.manifoldcf.agents.output.solr.ModifiedMultipartEntity.java

/**
 * Creates an instance using the specified parameters
 * @param mode the mode to use, may be {@code null}, in which case {@link HttpMultipartMode#STRICT} is used
 * @param boundary the boundary string, may be {@code null}, in which case {@link #generateBoundary()} is invoked to create the string
 * @param charset the character set to use, may be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
 *//*from  w w w .  j  av  a 2 s  .  c  o m*/
public ModifiedMultipartEntity(HttpMultipartMode mode, String boundary, Charset charset) {
    super();
    if (boundary == null) {
        boundary = generateBoundary();
    }
    if (mode == null) {
        mode = HttpMultipartMode.STRICT;
    }
    this.multipart = new ModifiedHttpMultipart("form-data", charset, boundary, mode);
    this.contentType = new BasicHeader(HTTP.CONTENT_TYPE, generateContentType(boundary, charset));
    this.dirty = true;
}

From source file:it.unipi.di.acube.batframework.systemPlugins.ERDSystem.java

@Override
public HashSet<Tag> solveC2W(String text) throws AnnotationException {
    lastTime = Calendar.getInstance().getTimeInMillis();
    HashSet<Tag> res = new HashSet<Tag>();
    try {//w w  w .j  a  v a 2 s  .co m
        URL erdApi = new URL(url);

        HttpURLConnection connection = (HttpURLConnection) erdApi.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
        multipartEntity.addPart("runID", new StringBody(this.run));
        multipartEntity.addPart("TextID", new StringBody("" + text.hashCode()));
        multipartEntity.addPart("Text", new StringBody(text));

        connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
        OutputStream out = connection.getOutputStream();
        try {
            multipartEntity.writeTo(out);
        } finally {
            out.close();
        }

        int status = ((HttpURLConnection) connection).getResponseCode();
        if (status != 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            String line = null;
            while ((line = br.readLine()) != null)
                System.err.println(line);
            throw new RuntimeException();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        while ((line = br.readLine()) != null) {
            String mid = line.split("\t")[2];
            String title = freebApi.midToTitle(mid);
            int wid;
            if (title == null || (wid = wikiApi.getIdByTitle(title)) == -1)
                System.err.println("Discarding mid=" + mid);
            else
                res.add(new Tag(wid));
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    lastTime = Calendar.getInstance().getTimeInMillis() - lastTime;
    return res;
}

From source file:nl.mineleni.cbsviewer.jsp.JSPIntegrationTest.java

/**
 * response validatie test tegen validator.nu
 * //from  w  w w.j a v  a2s.c  o  m
 * @param response
 *            test object
 * @throws Exception
 *             als er een fout optreedt tijdens de test.
 */
protected void boilerplateValidationTests(final HttpResponse response) throws Exception {

    final String body = new String(EntityUtils.toByteArray(response.getEntity()), "UTF-8");
    assertNotNull("De response body mag geen null zijn.", body);
    assertTrue("Response body dient met juiste prolog te starten.", body.startsWith(RESPONSEPROLOG));

    // online validation
    final HttpPost validatorrequest = new HttpPost(
            /* "http://html5.validator.nu/" */
            "https://validator.nu/");
    final HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT)
            .addTextBody("content", body, ContentType.APPLICATION_XHTML_XML)
            .addTextBody("schema",
                    "http://s.validator.nu/xhtml5-rdfalite.rnc http://s.validator.nu/html5/assertions.sch http://c.validator.nu/all/",
                    ContentType.DEFAULT_TEXT)
            .addTextBody("level", "error", ContentType.DEFAULT_TEXT)
            .addTextBody("parser", "xml", ContentType.DEFAULT_TEXT)
            // .addTextBody("parser", "html5", ContentType.DEFAULT_TEXT)
            .addTextBody("out", "json", ContentType.DEFAULT_TEXT).build();
    validatorrequest.setEntity(entity);
    final HttpResponse validatorresponse = validatorclient.execute(validatorrequest);

    assertThat("Validator response code.", Integer.valueOf(validatorresponse.getStatusLine().getStatusCode()),
            equalTo(SC_OK));

    final String validatorbody = new String(EntityUtils.toByteArray(validatorresponse.getEntity()), "UTF-8");
    LOGGER.debug("validator body:\n" + validatorbody);

    // controle op succes paragraaf in valadator response
    assertTrue("(X)HTML is niet geldig.", validatorbody.contains("<p class=\"success\">"));
}

From source file:org.apache.manifoldcf.agents.output.solr.ModifiedMultipartEntity.java

/**
 * Creates an instance using mode {@link HttpMultipartMode#STRICT}
 */
public ModifiedMultipartEntity() {
    this(HttpMultipartMode.STRICT, null, null);
}

From source file:eu.trentorise.opendata.jackan.test.ckan.ExperimentalCkanClient.java

/**
 * Uploads a file using file storage api, which I think is deprecated. As of
 * Aug 2015, coesn't work neither with demo.ckan.org nor dati.trentino
 *
 * Adapted from/*from   www.ja  v  a 2s .c  o  m*/
 * https://github.com/Ontodia/openrefine-ckan-storage-extension/blob/c99de78fd605c4754197668c9396cffd1f9a0267/src/org/deri/orefine/ckan/StorageApiProxy.java#L34
 */
public String uploadFile(String fileContent, String fileLabel) {
    HttpResponse formFields = null;
    try {
        String filekey = null;
        HttpClient client = new DefaultHttpClient();

        //   get the form fields required from ckan storage
        // notice if you put '3/' it gives not found :-/
        String formUrl = getCatalogUrl() + "/api/storage/auth/form/file/" + fileLabel;
        HttpGet getFormFields = new HttpGet(formUrl);
        getFormFields.setHeader("Authorization", getCkanToken());
        formFields = client.execute(getFormFields);
        HttpEntity entity = formFields.getEntity();
        if (entity != null) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            entity.writeTo(os);

            //now parse JSON
            //JSONObject obj = new JSONObject(os.toString());
            JsonNode obj = new ObjectMapper().readTree(os.toString());

            //post the file now
            String uploadFileUrl = getCatalogUrl() + obj.get("action").asText();
            HttpPost postFile = new HttpPost(uploadFileUrl);
            postFile.setHeader("Authorization", getCkanToken());
            MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.STRICT);

            //JSONArray fields = obj.getJSONArray("fields");
            Iterator<JsonNode> fields = obj.get("fields").elements();
            while (fields.hasNext()) {
                JsonNode fieldObj = fields.next();
                //JSONObject fieldObj = fields.getJSONObject(i);
                String fieldName = fieldObj.get("name").asText();
                String fieldValue = fieldObj.get("value").asText();
                if (fieldName.equals("key")) {
                    filekey = fieldValue;
                }
                mpEntity.addPart(fieldName,
                        new StringBody(fieldValue, "multipart/form-data", Charset.forName("UTF-8")));
            }

            /*
             for (int i = 0; i < fields.length(); i++) {
             //JSONObject fieldObj = fields.getJSONObject(i);
             JSONObject fieldObj = fields.getJSONObject(i);
             String fieldName = fieldObj.getString("name");
             String fieldValue = fieldObj.getString("value");
             if (fieldName.equals("key")) {
             filekey = fieldValue;
             }
             mpEntity.addPart(fieldName, new StringBody(fieldValue, "multipart/form-data", Charset.forName("UTF-8")));                    
             }
             */
            //   assure that we got the file key
            if (filekey == null) {
                throw new RuntimeException(
                        "failed to get the file key from CKAN storage form API. the response from " + formUrl
                                + " was: " + os.toString());
            }

            //the file should be the last part
            //hack... StringBody didn't work with large files
            mpEntity.addPart("file", new ByteArrayBody(fileContent.getBytes(Charset.forName("UTF-8")),
                    "multipart/form-data", fileLabel));

            postFile.setEntity(mpEntity);

            HttpResponse fileUploadResponse = client.execute(postFile);

            //check if the response status code was in the 200 range
            if (fileUploadResponse.getStatusLine().getStatusCode() < 200
                    || fileUploadResponse.getStatusLine().getStatusCode() >= 300) {
                throw new RuntimeException("failed to add the file to CKAN storage. response status line from "
                        + uploadFileUrl + " was: " + fileUploadResponse.getStatusLine());
            }
            return getCatalogUrl() + "/storage/f/" + filekey;

            //return CKAN_STORAGE_FILES_BASE_URI + filekey;
        }
        throw new RuntimeException("failed to get form details from CKAN storage. response line was: "
                + formFields.getStatusLine());
    } catch (IOException ioe) {
        throw new RuntimeException("failed to upload file to CKAN Storage ", ioe);
    }
}

From source file:com.jayway.restassured.config.HttpClientConfig.java

/**
 * Creates a new  HttpClientConfig instance with the <code>{@value org.apache.http.client.params.ClientPNames#COOKIE_POLICY}</code> parameter set to <code>{@value org.apache.http.client.params.CookiePolicy#IGNORE_COOKIES}</code>.
 *//*from   w ww  . java2  s. c  o m*/
public HttpClientConfig() {
    this.httpClientFactory = defaultHttpClientFactory();

    this.httpClientParams = new HashMap<String, Object>() {
        {
            put(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
            put(CookieSpecPNames.DATE_PATTERNS,
                    asList("EEE, dd-MMM-yyyy HH:mm:ss z", "EEE, dd MMM yyyy HH:mm:ss z"));
        }
    };
    this.httpMultipartMode = HttpMultipartMode.STRICT;
    this.shouldReuseHttpClientInstance = SHOULD_REUSE_HTTP_CLIENT_INSTANCE_BY_DEFAULT;
    this.httpClient = null;
    this.isUserConfigured = false;
}

From source file:ee.ioc.phon.netspeechapi.AudioUploader.java

public MultipartEntity createMultipartEntity(FileBody fileBody, String mimeType, int sampleRate) {
    // see: http://stackoverflow.com/questions/3014633
    //MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);

    try {/*  www  .  j  a  va2  s  .c o m*/
        entity.addPart("email", new StringBody(mEmail, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("MODEL_SAMPLE_RATE",
                new StringBody(String.valueOf(sampleRate), "text/plain", Charset.forName("UTF-8")));
        entity.addPart("DECODING", new StringBody(mDecodingSpeed, "text/plain", Charset.forName("UTF-8")));
        String sendEmailAsString = "0";
        if (mIsSendEmail) {
            sendEmailAsString = "1";
        }
        entity.addPart("SEND_EMAIL", new StringBody(sendEmailAsString, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("upload_wav", fileBody);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return entity;
}