Example usage for org.apache.http.entity.mime MultipartEntityBuilder create

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder create

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

From source file:org.brunocvcunha.instagram4j.requests.InstagramUploadStoryPhotoRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException//from   w ww.  ja  va  2s.c om
 * @throws IOException
 */
protected HttpEntity createMultipartEntity(String uploadId) throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", imageFile, ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:com.diversityarrays.dalclient.httpimpl.DalHttpFactoryImpl.java

@Override
public DalRequest createForUpload(String url, List<Pair<String, String>> pairs, String rand_num,
        String namesInOrder, String signature, Factory<InputStream> factory) {

    MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .addPart("uploadfile", new InputStreamBody(factory.create(), "uploadfile"))
            .addTextBody("rand_num", rand_num).addTextBody("url", url);

    for (Pair<String, String> pair : pairs) {
        builder.addTextBody(pair.a, pair.b);
    }/*from  w  w  w  . java 2 s .com*/

    HttpEntity entity = builder.addTextBody("param_order", namesInOrder).addTextBody("signature", signature)
            .build();

    HttpPost post = new HttpPost(url);
    post.setEntity(entity);
    return new DalRequestImpl(post);
}

From source file:com.cloudera.livy.client.http.LivyConnection.java

synchronized <V> V post(File f, Class<V> retType, String paramName, String uri, Object... uriParams)
        throws Exception {
    HttpPost post = new HttpPost();
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addPart(paramName, new FileBody(f));
    post.setEntity(builder.build());// w  w  w .  j ava  2s. c  o  m
    return sendRequest(post, retType, uri, uriParams);
}

From source file:de.siegmar.securetransfer.controller.MvcTest.java

@Test
public void messageWithoutFileWithoutPassword() throws Exception {
    final String messageToSend = "my secret message";

    final String boundary = "------TestBoundary" + UUID.randomUUID();
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setBoundary(boundary)
            .addTextBody("expirationDays", "1").addTextBody("message", messageToSend);

    // Create new message and expect redirect with flash message after store
    final MvcResult createMessageResult = mockMvc
            .perform(post("/send").content(ByteStreams.toByteArray(builder.build().getContent()))
                    .contentType(MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + boundary))
            .andExpect(status().isFound()).andExpect(redirectedUrlPattern("/send/**"))
            .andExpect(flash().attribute("message", messageToSend)).andReturn();

    // receive data after redirect
    final String messageStatusUrl = createMessageResult.getResponse().getRedirectedUrl();

    final MvcResult messageStatusResult = mockMvc.perform(get(messageStatusUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("send/message_status")).andReturn();

    final SenderMessage senderMessage = (SenderMessage) messageStatusResult.getModelAndView().getModel()
            .get("senderMessage");

    assertNotNull(senderMessage);/*from  w w  w.j av a2s .c  om*/
    assertNotNull(senderMessage.getId());
    assertNotNull(senderMessage.getReceiverId());
    assertNotNull(senderMessage.getExpiration());
    assertNull(senderMessage.getReceived());
    assertFalse(senderMessage.isPasswordEncrypted());

    final String receiveUrl = (String) messageStatusResult.getModelAndView().getModel().get("receiveUrl");

    assertNotNull(receiveUrl);

    final String linkSecret = messageStatusUrl.replaceFirst(".*linkSecret=", "");
    HashCode.fromString(linkSecret);

    // call receiver URL
    final MvcResult confirmPage = mockMvc.perform(get(receiveUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("receive/message_confirm")).andReturn();

    final Document confirmPageDoc = Jsoup.parse(confirmPage.getResponse().getContentAsString());
    final String confirmUrl = confirmPageDoc.getElementsByTag("form").attr("action");

    // Receive message
    final MvcResult messageResult = mockMvc.perform(get(confirmUrl).param("linkSecret", linkSecret))
            .andExpect(status().isOk()).andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("receive/message")).andReturn();

    final DecryptedMessage decryptedMessage = (DecryptedMessage) messageResult.getModelAndView().getModel()
            .get("decryptedMessage");

    assertEquals(messageToSend, decryptedMessage.getMessage());
    assertEquals(0, decryptedMessage.getFiles().size());

    // Check message is burned
    mockMvc.perform(get(receiveUrl)).andExpect(status().isNotFound())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("message_not_found"));

    // Check sender status page
    final MvcResult messageStatusResult2 = mockMvc.perform(get(messageStatusUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("send/message_status")).andReturn();

    final SenderMessage senderMessage2 = (SenderMessage) messageStatusResult2.getModelAndView().getModel()
            .get("senderMessage");

    assertNotNull(senderMessage2);
    assertNotNull(senderMessage2.getId());
    assertNotNull(senderMessage2.getReceiverId());
    assertNotNull(senderMessage2.getExpiration());
    assertNotNull(senderMessage2.getReceived());
    assertFalse(senderMessage.isPasswordEncrypted());
}

From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java

/**
 * Upload metadata file.//from   ww w .j  av  a  2 s  . c o  m
 *
 * @param endPoint the end point
 * @param xml the xml
 * @param client the client (optional)
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws JSONException the JSON exception
 */
private static String uploadMetadataFile(String endPoint, InputStream xml, CloseableHttpClient client)
        throws IOException, JSONException {

    boolean close = false;
    if (client == null) {
        client = HttpClients.createDefault();
        close = true;
    }

    try {

        HttpPost request = new HttpPost(endPoint + TestObjects_URL + "?action=upload");

        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept", ACCEPT);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("fileupload", xml, ContentType.TEXT_XML, "file.xml");
        HttpEntity entity = builder.build();

        request.setEntity(entity);

        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {

            ResponseHandler<String> handler = new BasicResponseHandler();
            String body = handler.handleResponse(response);
            JSONObject jsonRoot = new JSONObject(body);
            return jsonRoot.getJSONObject("testObject").getString("id");
        } else {
            Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: "
                    + response.getStatusLine().getStatusCode() + " for " + TestObjects_URL);
            return null;
        }
    } catch (Exception e) {
        Log.error(Log.SERVICE, "Error calling INSPIRE service: " + endPoint, e);
        return null;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }
}

From source file:functionaltests.RestSchedulerJobTaskTest.java

@Test
public void testLoginWithCredentials() throws Exception {
    RestFuncTestConfig config = RestFuncTestConfig.getInstance();
    Credentials credentials = RestFuncTUtils.createCredentials(config.getLogin(), config.getPassword(),
            RestFuncTHelper.getSchedulerPublicKey());
    String schedulerUrl = getResourceUrl("login");
    HttpPost httpPost = new HttpPost(schedulerUrl);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().addPart("credential",
            new ByteArrayBody(credentials.getBase64(), ContentType.APPLICATION_OCTET_STREAM, null));
    httpPost.setEntity(multipartEntityBuilder.build());
    HttpResponse response = executeUriRequest(httpPost);
    assertHttpStatusOK(response);/*w w w . j  a  va  2s . co  m*/
    String sessionId = assertContentNotEmpty(response);

    String currentUserUrl = getResourceUrl("logins/sessionid/" + sessionId);

    HttpGet httpGet = new HttpGet(currentUserUrl);
    response = executeUriRequest(httpGet);
    assertHttpStatusOK(response);
    String userName = assertContentNotEmpty(response);
    Assert.assertEquals(config.getLogin(), userName);
}

From source file:org.jodconverter.task.OnlineConversionTask.java

@Override
public void execute(final OfficeContext context) throws OfficeException {

    LOGGER.info("Executing online conversion task...");
    final OnlineOfficeContext onlineContext = (OnlineOfficeContext) context;

    // Obtain a source file that can be loaded by office. If the source
    // is an input stream, then a temporary file will be created from the
    // stream. The temporary file will be deleted once the task is done.
    final File sourceFile = source.getFile();
    try {/* w w w.  j  a v a 2  s . co m*/

        // Get the target file (which is a temporary file if the
        // output target is an output stream).
        final File targetFile = target.getFile();

        try {
            // TODO: Add the ability to pass on a custom charset to FileBody

            // See https://github.com/LibreOffice/online/blob/master/wsd/reference.txt
            final HttpEntity entity = MultipartEntityBuilder.create().addPart("data", new FileBody(sourceFile))
                    .build();

            // Use the fluent API to post the file and
            // save the response into the target file.
            final RequestConfig requestConfig = onlineContext.getRequestConfig();
            final URIBuilder uriBuilder = new URIBuilder(buildUrl(requestConfig.getUrl()));

            // We suppose that the server supports custom load properties,
            // but LibreOffice does not support custom load properties,
            // only the sample web service do.
            addPropertiesToBuilder(uriBuilder, target.getFormat().getLoadProperties(),
                    LOAD_PROPERTIES_PREFIX_PARAM);

            // We suppose that the server supports custom store properties,
            // but LibreOffice does not support custom store properties,
            // only the sample web service do.
            addPropertiesToBuilder(uriBuilder,
                    target.getFormat().getStoreProperties(source.getFormat().getInputFamily()),
                    STORE_PROPERTIES_PREFIX_PARAM);

            Executor.newInstance(onlineContext.getHttpClient()).execute(
                    // Request.Post(buildUrl(requestConfig.getUrl()))
                    Request.Post(uriBuilder.build()).connectTimeout(requestConfig.getConnectTimeout())
                            .socketTimeout(requestConfig.getSocketTimeout()).body(entity))
                    .saveContent(targetFile);

            // onComplete on target will copy the temp file to
            // the OutputStream and then delete the temp file
            // if the output is an OutputStream
            target.onComplete(targetFile);

        } catch (Exception ex) {
            LOGGER.error("Online conversion failed.", ex);
            final OfficeException officeEx = new OfficeException("Online conversion failed", ex);
            target.onFailure(targetFile, officeEx);
            throw officeEx;
        }

    } finally {

        // Here the source file is no longer required so we can delete
        // any temporary file that has been created if required.
        source.onConsumed(sourceFile);
    }
}

From source file:hspc.submissionsprogram.AppDisplay.java

AppDisplay() {
    this.setTitle("Dominion High School Programming Contest");
    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    this.setResizable(false);

    WindowListener exitListener = new WindowAdapter() {
        @Override//from  w w w .  j ava2s. co m
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    };
    this.addWindowListener(exitListener);

    JTabbedPane pane = new JTabbedPane();
    this.add(pane);

    JPanel submitPanel = new JPanel(null);
    submitPanel.setPreferredSize(new Dimension(500, 500));

    UIManager.put("FileChooser.readOnly", true);
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setBounds(0, 0, 500, 350);
    fileChooser.setVisible(true);
    FileNameExtensionFilter javaFilter = new FileNameExtensionFilter("Java files (*.java)", "java");
    fileChooser.setFileFilter(javaFilter);
    fileChooser.setAcceptAllFileFilterUsed(false);
    fileChooser.setControlButtonsAreShown(false);
    submitPanel.add(fileChooser);

    JSeparator separator1 = new JSeparator();
    separator1.setBounds(12, 350, 476, 2);
    separator1.setForeground(new Color(122, 138, 152));
    submitPanel.add(separator1);

    JLabel problemChooserLabel = new JLabel("Problem:");
    problemChooserLabel.setBounds(12, 360, 74, 25);
    submitPanel.add(problemChooserLabel);

    String[] listOfProblems = Main.Configuration.get("problem_names")
            .split(Main.Configuration.get("name_delimiter"));
    JComboBox problems = new JComboBox<>(listOfProblems);
    problems.setBounds(96, 360, 393, 25);
    submitPanel.add(problems);

    JButton submit = new JButton("Submit");
    submit.setBounds(170, 458, 160, 30);
    submit.addActionListener(e -> {
        try {
            File file = fileChooser.getSelectedFile();
            try {
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpPost uploadFile = new HttpPost(Main.Configuration.get("submit_url"));

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.addTextBody("accountID", Main.accountID, ContentType.TEXT_PLAIN);
                builder.addTextBody("problem", String.valueOf(problems.getSelectedItem()),
                        ContentType.TEXT_PLAIN);
                builder.addBinaryBody("submission", file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
                HttpEntity multipart = builder.build();

                uploadFile.setEntity(multipart);

                CloseableHttpResponse response = httpClient.execute(uploadFile);
                HttpEntity responseEntity = response.getEntity();
                String inputLine;
                BufferedReader br = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
                try {
                    if ((inputLine = br.readLine()) != null) {
                        int rowIndex = Integer.parseInt(inputLine);
                        new ResultWatcher(rowIndex);
                    }
                    br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } catch (NullPointerException ex) {
            JOptionPane.showMessageDialog(this, "No file selected.\nPlease select a java file.", "Error",
                    JOptionPane.WARNING_MESSAGE);
        }
    });
    submitPanel.add(submit);

    JPanel clarificationsPanel = new JPanel(null);
    clarificationsPanel.setPreferredSize(new Dimension(500, 500));

    cList = new JList<>();
    cList.setBounds(12, 12, 476, 200);
    cList.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)),
            BorderFactory.createEmptyBorder(8, 8, 8, 8)));
    cList.setBackground(new Color(254, 254, 255));
    clarificationsPanel.add(cList);

    JButton viewC = new JButton("View");
    viewC.setBounds(12, 224, 232, 25);
    viewC.addActionListener(e -> {
        if (cList.getSelectedIndex() != -1) {
            int id = Integer.parseInt(cList.getSelectedValue().split("\\.")[0]);
            clarificationDatas.stream().filter(data -> data.getId() == id).forEach(
                    data -> new ClarificationDisplay(data.getProblem(), data.getText(), data.getResponse()));
        }
    });
    clarificationsPanel.add(viewC);

    JButton refreshC = new JButton("Refresh");
    refreshC.setBounds(256, 224, 232, 25);
    refreshC.addActionListener(e -> updateCList(true));
    clarificationsPanel.add(refreshC);

    JSeparator separator2 = new JSeparator();
    separator2.setBounds(12, 261, 476, 2);
    separator2.setForeground(new Color(122, 138, 152));
    clarificationsPanel.add(separator2);

    JLabel problemChooserLabelC = new JLabel("Problem:");
    problemChooserLabelC.setBounds(12, 273, 74, 25);
    clarificationsPanel.add(problemChooserLabelC);

    JComboBox problemsC = new JComboBox<>(listOfProblems);
    problemsC.setBounds(96, 273, 393, 25);
    clarificationsPanel.add(problemsC);

    JTextArea textAreaC = new JTextArea();
    textAreaC.setLineWrap(true);
    textAreaC.setWrapStyleWord(true);
    textAreaC.setBorder(new CompoundBorder(BorderFactory.createLineBorder(new Color(122, 138, 152)),
            BorderFactory.createEmptyBorder(8, 8, 8, 8)));
    textAreaC.setBackground(new Color(254, 254, 255));

    JScrollPane areaScrollPane = new JScrollPane(textAreaC);
    areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    areaScrollPane.setBounds(12, 312, 477, 134);
    clarificationsPanel.add(areaScrollPane);

    JButton submitC = new JButton("Submit Clarification");
    submitC.setBounds(170, 458, 160, 30);
    submitC.addActionListener(e -> {
        if (textAreaC.getText().length() > 2048) {
            JOptionPane.showMessageDialog(this,
                    "Clarification body is too long.\nMaximum of 2048 characters allowed.", "Error",
                    JOptionPane.WARNING_MESSAGE);
        } else if (textAreaC.getText().length() < 20) {
            JOptionPane.showMessageDialog(this,
                    "Clarification body is too short.\nClarifications must be at least 20 characters, but no more than 2048.",
                    "Error", JOptionPane.WARNING_MESSAGE);
        } else {
            Connection conn = null;
            PreparedStatement stmt = null;
            try {
                Class.forName(JDBC_DRIVER);

                conn = DriverManager.getConnection(Main.Configuration.get("jdbc_mysql_address"),
                        Main.Configuration.get("mysql_user"), Main.Configuration.get("mysql_pass"));

                String sql = "INSERT INTO clarifications (team, problem, text) VALUES (?, ?, ?)";
                stmt = conn.prepareStatement(sql);

                stmt.setInt(1, Integer.parseInt(String.valueOf(Main.accountID)));
                stmt.setString(2, String.valueOf(problemsC.getSelectedItem()));
                stmt.setString(3, String.valueOf(textAreaC.getText()));

                textAreaC.setText("");

                stmt.executeUpdate();

                stmt.close();
                conn.close();

                updateCList(false);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (stmt != null) {
                        stmt.close();
                    }
                } catch (Exception ex2) {
                    ex2.printStackTrace();
                }
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (Exception ex2) {
                    ex2.printStackTrace();
                }
            }
        }
    });
    clarificationsPanel.add(submitC);

    pane.addTab("Submit", submitPanel);
    pane.addTab("Clarifications", clarificationsPanel);

    Timer timer = new Timer();
    TimerTask updateTask = new TimerTask() {
        @Override
        public void run() {
            updateCList(false);
        }
    };
    timer.schedule(updateTask, 10000, 10000);

    updateCList(false);

    this.pack();
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}

From source file:org.sead.repositories.reference.util.SEADGoogleLogin.java

static void getAuthCode() {
    access_token = null;//  w  ww  . ja v  a 2  s.c om
    expires_in = -1;
    token_start_time = -1;
    refresh_token = null;
    new File("refresh.txt").delete();

    if (gProps == null) {
        initGProps();
    }

    // Contact google for a user code
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {

        String codeUri = gProps.auth_uri.substring(0, gProps.auth_uri.length() - 4) + "device/code";

        HttpPost codeRequest = new HttpPost(codeUri);

        MultipartEntityBuilder meb = MultipartEntityBuilder.create();
        meb.addTextBody("client_id", gProps.client_id);
        meb.addTextBody("scope", "email profile");
        HttpEntity reqEntity = meb.build();

        codeRequest.setEntity(reqEntity);
        CloseableHttpResponse response = httpclient.execute(codeRequest);
        try {

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String responseJSON = EntityUtils.toString(resEntity);
                    ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
                    device_code = root.get("device_code").asText();
                    user_code = root.get("user_code").asText();
                    verification_url = root.get("verification_url").asText();
                    expires_in = root.get("expires_in").asInt();
                }
            } else {
                log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
            }
        } finally {
            response.close();
            httpclient.close();
        }
    } catch (IOException e) {
        log.error("Error reading sead-google.json or making http requests for code.");
        log.error(e.getMessage());
    }
}

From source file:net.duckling.ddl.util.RESTClient.java

public JsonObject httpUpload(String url, String dataFieldName, byte[] data, List<NameValuePair> params) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from  w  w  w  . j  a  va  2s  . c o  m*/
        HttpPost httppost = new HttpPost(url);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                .addBinaryBody(dataFieldName, data, ContentType.DEFAULT_BINARY, "tempfile");
        for (NameValuePair hp : params) {
            builder.addPart(hp.getName(),
                    new StringBody(hp.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
        }
        HttpEntity reqEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build();
        httppost.setEntity(reqEntity);
        CloseableHttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            JsonParser jp = new JsonParser();
            JsonElement je = jp.parse(br);
            return je.getAsJsonObject();
        } finally {
            response.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}