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

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

Introduction

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

Prototype

public MultipartEntityBuilder addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

From source file:com.lehman.ic9.net.httpClient.java

/**
 * Sets request information for the type of POST request. This is determined 
 * by the post type provided./* w  w  w  . j a v  a  2  s .  co m*/
 * @param postTypeStr is a String with the postType.
 * @param Obj is a Javascript object to set for the request.
 * @param ContentType is a String with the content-type for the custom request.
 * @throws ic9exception Exception
 * @throws UnsupportedEncodingException Exception
 */
@SuppressWarnings("unchecked")
private void setPostInfo(String postTypeStr, Object Obj, String ContentType)
        throws ic9exception, UnsupportedEncodingException {
    postType pt = this.getPostType(postTypeStr);
    if (pt == postType.URL_ENCODED) {
        Map<String, Object> jobj = (Map<String, Object>) Obj;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (String key : jobj.keySet()) {
            Object val = jobj.get(key);
            nvps.add(new BasicNameValuePair(key, val.toString()));
        }
        this.respEnt = new UrlEncodedFormEntity(nvps);
    } else if (pt == postType.MULTIPART) {
        MultipartEntityBuilder mpEntBuilder = MultipartEntityBuilder.create();
        Map<String, Object> jobj = (Map<String, Object>) Obj;
        for (String key : jobj.keySet()) {
            Map<String, Object> part = (Map<String, Object>) jobj.get(key);
            if (part.containsKey("name") && part.containsKey("data")) {
                String pkey = (String) part.get("name");
                if (part.get("data") instanceof byte[]) {
                    byte[] data = (byte[]) part.get("data");
                    mpEntBuilder.addPart(key, new ByteArrayBody(data, pkey));
                } else if (part.get("data") instanceof String) {
                    String data = (String) part.get("data");
                    mpEntBuilder.addPart(key,
                            new StringBody(data, org.apache.http.entity.ContentType.DEFAULT_TEXT));
                }
            } else
                throw new ic9exception(
                        "httpClient.setPotInfo(): Multipart from data expects and object of httpPart objects.");
        }
        this.respEnt = mpEntBuilder.build();
    } else {
        if (Obj instanceof String) {
            StringEntity se = new StringEntity((String) Obj);
            if (ContentType != null)
                se.setContentType(ContentType);
            else
                throw new ic9exception(
                        "httpClient.setPostInfo(): For custom postType, the third argument for content-type must be set.");
            this.respEnt = se;
        } else if (Obj instanceof Map) {
            Map<String, Object> tobj = (Map<String, Object>) Obj;

            if (tobj.containsKey("data") && tobj.get("data") instanceof byte[]) {
                if (ContentType != null) {
                    ByteArrayEntity bae = new ByteArrayEntity((byte[]) Obj);
                    bae.setContentType(ContentType);
                    this.respEnt = bae;
                } else
                    throw new ic9exception(
                            "httpClient.setPostInfo(): For custom postType, the third argument for content-type must be set.");
            } else
                throw new ic9exception(
                        "httpClient.setPostInfo(): Provided object is not of type Buffer or is missing 'data' attribute. (data should be byte[])");
        } else
            throw new ic9exception(
                    "httpClient.setPostInfo(): Second argument to POST call expecting String or Buffer object.");
    }
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

void buildFilePart(final KeyDataPair pairWithFile, final MultipartEntityBuilder builder) throws IOException {
    String mimeType = pairWithFile.getMimeType();
    if (mimeType == null) {
        mimeType = "application/octet-stream";
    }//  w w  w . j av a  2 s .  c o  m

    final ContentType contentType = ContentType.create(mimeType);
    final File file = pairWithFile.getFile();

    if (pairWithFile.getData() != null) {
        final String filename;
        if (file == null) {
            filename = pairWithFile.getValue();
        } else if (webClient_.getBrowserVersion().hasFeature(HEADER_CONTENT_DISPOSITION_ABSOLUTE_PATH)) {
            filename = file.getAbsolutePath();
        } else {
            filename = file.getName();
        }

        builder.addBinaryBody(pairWithFile.getName(), new ByteArrayInputStream(pairWithFile.getData()),
                contentType, filename);
        return;
    }

    if (file == null) {
        builder.addPart(pairWithFile.getName(),
                // Overridden in order not to have a chunked response.
                new InputStreamBody(new ByteArrayInputStream(new byte[0]), contentType,
                        pairWithFile.getValue()) {
                    @Override
                    public long getContentLength() {
                        return 0;
                    }
                });
        return;
    }

    String filename;
    if (pairWithFile.getFile() == null) {
        filename = pairWithFile.getValue();
    } else if (webClient_.getBrowserVersion().hasFeature(HEADER_CONTENT_DISPOSITION_ABSOLUTE_PATH)) {
        filename = pairWithFile.getFile().getAbsolutePath();
    } else {
        filename = pairWithFile.getFile().getName();
    }
    builder.addBinaryBody(pairWithFile.getName(), pairWithFile.getFile(), contentType, filename);
}

From source file:gov.osti.services.Metadata.java

/**
 * Send this Metadata to the ARCHIVER external support process.
 *
 * Needs a CODE ID and one of either an ARCHIVE FILE or REPOSITORY LINK.
 *
 * If nothing supplied to archive, do nothing.
 *
 * @param codeId the CODE ID for this METADATA
 * @param repositoryLink (optional) the REPOSITORY LINK value, or null if none
 * @param archiveFile (optional) the File recently uploaded to ARCHIVE, or null if none
 * @param archiveContainer (optional) the Container recently uploaded to ARCHIVE, or null if none
 * @throws IOException on IO transmission errors
 */// ww  w.j a  v  a2  s . co  m
private static void sendToArchiver(Long codeId, String repositoryLink, File archiveFile, File archiveContainer)
        throws IOException {
    if ("".equals(ARCHIVER_URL))
        return;

    // Nothing sent?
    if (StringUtils.isBlank(repositoryLink) && null == archiveFile && null == archiveContainer)
        return;

    // set up a connection
    CloseableHttpClient hc = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom()
            .setSocketTimeout(300000).setConnectTimeout(300000).setConnectionRequestTimeout(300000).build())
            .build();

    try {
        HttpPost post = new HttpPost(ARCHIVER_URL);
        // attributes to send
        ObjectNode request = mapper.createObjectNode();
        request.put("code_id", codeId);
        request.put("repository_link", repositoryLink);

        // determine if there's a file to send or not
        if (null == archiveFile && null == archiveContainer) {
            post.setHeader("Content-Type", "application/json");
            post.setHeader("Accept", "application/json");

            post.setEntity(new StringEntity(request.toString(), "UTF-8"));
        } else {
            MultipartEntityBuilder mpe = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("project", new StringBody(request.toString(), ContentType.APPLICATION_JSON));

            if (archiveFile != null)
                mpe.addPart("file", new FileBody(archiveFile, ContentType.DEFAULT_BINARY));

            if (archiveContainer != null)
                mpe.addPart("container", new FileBody(archiveContainer, ContentType.DEFAULT_BINARY));

            post.setEntity(mpe.build());
        }
        HttpResponse response = hc.execute(post);

        int statusCode = response.getStatusLine().getStatusCode();

        if (HttpStatus.SC_OK != statusCode && HttpStatus.SC_CREATED != statusCode) {
            throw new IOException("Archiver Error: " + EntityUtils.toString(response.getEntity()));
        }
    } catch (IOException e) {
        log.warn("Archiver request error: " + e.getMessage());
        throw e;
    } finally {
        try {
            if (null != hc)
                hc.close();
        } catch (IOException e) {
            log.warn("Close Error: " + e.getMessage());
        }
    }
}

From source file:co.beem.project.beem.FbTextService.java

private void uploadPicture(ImageMessageInQueue imageMessageInQueue, String pageId, String accessToken,
        String message) throws ClientProtocolException, IOException {
    String url = String.format(
            "https://graph.facebook.com/v2.3/%s/photos/?access_token=%s&published=false&message=%s", pageId,
            accessToken, message);//from w  w  w  .  ja  va2  s.  c o m
    HttpPost post = new HttpPost(url);
    HttpClient client = new DefaultHttpClient();
    //Image attaching
    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
    File file = new File(imageMessageInQueue.getLocalPath());
    Bitmap bi = decodeFile(file);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bi.compress(Bitmap.CompressFormat.JPEG, 65, baos);
    byte[] data = baos.toByteArray();
    ByteArrayBody byteArrayBody = new ByteArrayBody(data, file.getName());
    //multipartEntity.addBinaryBody("source", file, ContentType.create("image/jpeg"), file.getName());
    multipartEntity.addPart("source", byteArrayBody);
    post.setEntity(multipartEntity.build());
    HttpResponse response = client.execute(post);
    HttpEntity resEntity = response.getEntity();
    final String response_str = EntityUtils.toString(resEntity);
    if (FbTextApplication.isDebug)
        Log.v(TAG, "response entity: " + response_str);
    int statusCode = response.getStatusLine().getStatusCode();
    if (FbTextApplication.isDebug)
        Log.v(TAG, "response status code: " + statusCode);

    //get image link here
    if (200 != statusCode) {
        sendBroadcastPhotoResult(false, imageMessageInQueue, "");
        // update database this failure
        saveMessageImageSentStatus(imageMessageInQueue, false);
    } else
        try {
            String photoPostId = new Gson().fromJson(response_str, FbPost.class).getId();
            URL fbPhoto = new URL(
                    String.format("https://graph.facebook.com/v2.3/%s?access_token=%s&fields=images",
                            photoPostId, accessToken));
            HttpURLConnection urlConnection = (HttpURLConnection) fbPhoto.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            String postDetailString = "";
            if (null != inputStream)
                postDetailString = getStringFromInputStream(inputStream);
            if (FbTextApplication.isDebug)
                Log.v(TAG, postDetailString);
            if (postDetailString != null && postDetailString.length() > 1) {
                FbPhoto photo = new Gson().fromJson(postDetailString, FbPhoto.class);
                if (photo != null && photo.getImages() != null) {
                    boolean isSentLinkSuccess = true;
                    try {
                        BeemChatManager chatManager = getChatManager();
                        if (chatManager != null) {
                            ChatAdapter adapter = chatManager.getChat(imageMessageInQueue.getjIdWithRes());
                            Log.e(TAG, "jId with res: " + imageMessageInQueue.getjIdWithRes());
                            BeemMessage msgToSend = new BeemMessage(imageMessageInQueue.getjIdWithRes(),
                                    BeemMessage.MSG_TYPE_CHAT);
                            msgToSend.setBody(" sent you a photo " + photo.getImages().get(0).getSource());
                            if (adapter != null) {
                                adapter.sendMessage(msgToSend);
                            } else {
                                IChat newChat = chatManager.createChat(imageMessageInQueue.getjIdWithRes(),
                                        null);
                                newChat.sendMessage(msgToSend);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        isSentLinkSuccess = false;
                    }

                    sendBroadcastPhotoResult(isSentLinkSuccess, imageMessageInQueue,
                            photo.getImages().get(0).getSource());
                    // save image as sent
                    saveMessageImageSentStatus(imageMessageInQueue, isSentLinkSuccess);

                    //sleep a while after sent successfull
                    try {
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            sendBroadcastPhotoResult(false, imageMessageInQueue, " ");
            saveMessageImageSentStatus(imageMessageInQueue, false);
        }
}

From source file:service.OrderService.java

private String sendRequestForUnloadInShop(Order order, ServiceResult result) throws Exception {
    List<String> missing = new ArrayList();
    List<String> directionNames = new ArrayList();
    for (Direction dir : order.getDirections()) {
        String dirName = (dir.getNameForShop() != null ? dir.getNameForShop() : "");
        if (dirName.isEmpty()) {
            missing.add(//from w  w w .j  a va2 s . co  m
                    "? ?    ? ? "
                            + dir.getName());
        }
        directionNames.add(dirName);
    }
    String orderName = "";
    if (order.getOrderType() != null && order.getOrderType().getNameForShop() != null) {
        orderName = order.getOrderType().getNameForShop();
    }
    if (orderName.isEmpty()) {
        missing.add(
                "? ?    ?  ");
    }
    String subject = (order.getSubject() != null ? order.getSubject() : "");
    if (subject.isEmpty()) {
        missing.add(" ");
    }
    String price = (order.getCost() != null ? order.getCost().toString() : "0");
    String numberOfPages = (order.getNumberOfPages() != null ? order.getNumberOfPages() : "");
    if (numberOfPages.isEmpty()) {
        missing.add("? ?");
    }
    String fileName = "order" + order.getOrderId() + ".zip";

    if (missing.isEmpty()) {
        String url = "http://zaochnik5.ru/up/uploadfile.php";
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder multipart = MultipartEntityBuilder.create();
        multipart.addTextBody("type_work", orderName);
        multipart.addTextBody("name_work", subject);
        multipart.addTextBody("price", price);
        multipart.addTextBody("table_of_contents", "-");
        for (String dirName : directionNames) {
            multipart.addTextBody("napravlenie", dirName);
        }
        multipart.addTextBody("kol-vo_str", numberOfPages);
        multipart.addTextBody("fail", fileName);
        multipart.addTextBody("order_number", order.getOrderId().toString());
        multipart.addTextBody("kol-vo_order", "1");
        multipart.addTextBody("published", "0");
        multipart.addTextBody("srvkey", "8D9ucTqL4Ga2ZkLCmctR");
        byte[] zipBytes = getZipAllReadyFiles(order);
        multipart.addPart("upload", new ByteArrayBody(zipBytes, fileName));
        HttpEntity ent = multipart.build();
        post.setEntity(ent);
        HttpClient client = HttpClients.createDefault();
        HttpResponse response = client.execute(post);
        return IOUtils.toString(response.getEntity().getContent());
    } else {
        String missingStr = "";
        for (String str : missing) {
            missingStr += str + ", ";
        }
        result.addError(
                "?  ,  ?  :"
                        + missingStr);
        return "";
    }
}

From source file:SubmitResults.java

private File populateRequest(final Main parent, String formStatus, String filePath, HttpPost req,
        final String changeIdXSLT, ContentType ct, MultipartEntityBuilder entityBuilder,
        final String newIdent) {

    File ammendedFile = null;/*from   ww  w  .ja v a2 s  .c  om*/

    final File instanceFile = new File(filePath);

    if (formStatus != null) {
        System.out.println("Setting form status in header: " + formStatus);
        req.setHeader("form_status", formStatus); // smap add form_status header
    } else {
        System.out.println("Form Status null");
    }

    if (newIdent != null) {
        // Transform the survey ID
        try {
            System.out.println("Transformaing Instance file: " + instanceFile);
            PipedInputStream in = new PipedInputStream();
            final PipedOutputStream outStream = new PipedOutputStream(in);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        InputStream xslStream = new ByteArrayInputStream(changeIdXSLT.getBytes("UTF-8"));
                        Transformer transformer = TransformerFactory.newInstance()
                                .newTransformer(new StreamSource(xslStream));
                        StreamSource source = new StreamSource(instanceFile);
                        StreamResult out = new StreamResult(outStream);
                        transformer.setParameter("surveyId", newIdent);
                        transformer.transform(source, out);
                        outStream.close();
                    } catch (TransformerConfigurationException e1) {
                        parent.appendToStatus("Error changing ident: " + e1.toString());
                    } catch (TransformerFactoryConfigurationError e1) {
                        parent.appendToStatus("Error changing ident: " + e1.toString());
                    } catch (TransformerException e) {
                        parent.appendToStatus("Error changing ident: " + e.toString());
                    } catch (IOException e) {
                        parent.appendToStatus("Error changing ident: " + e.toString());
                    }
                }
            }).start();
            System.out.println("Saving stream to file");
            ammendedFile = saveStreamTemp(in);
        } catch (Exception e) {
            parent.appendToStatus("Error changing ident: " + e.toString());
        }
    }

    /*
     * Add submission file as file body, hence save to temporary file first
     */
    if (newIdent == null) {
        ct = ContentType.create("text/xml");
        entityBuilder.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath());
    } else {
        FileBody fb = new FileBody(ammendedFile);
        entityBuilder.addPart("xml_submission_file", fb);
    }

    parent.appendToStatus("Instance file path: " + instanceFile.getPath());

    /*
     *  find all files referenced by the survey
     *  Temporarily check to see if the parent directory is "uploadedSurveys". If it is
     *   then we will need to scan the submission file to get the list of attachments to 
     *   send. 
     *  Alternatively this is a newly submitted survey stored in its own directory just as
     *  surveys are stored on the phone.  We can then just add all the surveys that are in 
     *  the same directory as the submission file.
     */
    File[] allFiles = instanceFile.getParentFile().listFiles();

    // add media files ignoring invisible files and the submission file
    List<File> files = new ArrayList<File>();
    for (File f : allFiles) {
        String fileName = f.getName();
        if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) { // ignore invisible files and instance xml file    
            files.add(f);
        }
    }

    for (int j = 0; j < files.size(); j++) {

        File f = files.get(j);
        String fileName = f.getName();
        ct = ContentType.create(getContentType(parent, fileName));
        FileBody fba = new FileBody(f, ct, fileName);
        entityBuilder.addPart(fileName, fba);

    }

    req.setEntity(entityBuilder.build());

    return ammendedFile;
}

From source file:wsserver.EKF1TimerSessionBean.java

private boolean postMultipartSectUpd(List<CbEkfgroupUpd1csectToBx> uswps) {
    String charset = "UTF-8";
    String requestURL = systemURL + "bitrix/ekflibraries/corpbus/manipulate_data.php";
    boolean reply = true;
    String sreply = "";

    if (uswps.isEmpty())
        return reply;
    long allFileSize = 0;

    String logStr = "Upd sect cnt=" + uswps.size() + ". ";
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {//  w w w  .  ja v  a2s.  c om
        MultipartUtility multipart = new MultipartUtility(requestURL, charset);
        HttpPost httppost = new HttpPost(requestURL);
        MultipartEntityBuilder reqBuilder = MultipartEntityBuilder.create();

        multipart.addHeaderField("User-Agent", "CodeJava");
        httppost.addHeader("User-Agent", "CodeJava");
        multipart.addHeaderField("Test-Header", "Header-Value");
        int index = 0;
        multipart.addFormField("OTYPE", "UPDATE");
        reqBuilder.addPart("OTYPE", new StringBody("UPDATE", ContentType.TEXT_PLAIN));
        multipart.addFormField("ENTITY", "1CSECT");
        reqBuilder.addPart("ENTITY", new StringBody("1CSECT", ContentType.TEXT_PLAIN));
        int ocnt = uswps.size();
        multipart.addFormField("OCNT", "" + ocnt);
        reqBuilder.addPart("OCNT", new StringBody("" + ocnt, ContentType.TEXT_PLAIN));
        //String logStr=""; 
        for (CbEkfgroupUpd1csectToBx npwp : uswps) {
            multipart.addFormField("SID" + index, npwp.getSid());
            reqBuilder.addPart("SID" + index, new StringBody(npwp.getSid(), ContentType.TEXT_PLAIN));
            //if(!npwp.getSid().equals(npwp.getCbBxgroupId()))
            //    multipart.addFormField("SETSID"+index, "1");
            //else
            //    multipart.addFormField("SETSID"+index, "0");
            //multipart.addFormField("NEWSID"+index, npwp.getCbBxgroupId());

            logStr += "[" + index + "] NAME " + npwp.getBxname() + "," + npwp.getF1cname() + ","
                    + npwp.getBxparentId() + "," + npwp.getF1cparentId();

            if (!npwp.getBxname().equals(npwp.getF1cname())) {
                multipart.addFormField("SETSNAME" + index, "1");
                reqBuilder.addPart("SETSNAME" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSNAME" + index, "0");
                reqBuilder.addPart("SETSNAME" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            if (!npwp.getBxparentId().equals(npwp.getF1cparentId())) {
                multipart.addFormField("SETSGRXMLID" + index, "1");
                reqBuilder.addPart("SETSGRXMLID" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSGRXMLID" + index, "0");
                reqBuilder.addPart("SETSGRXMLID" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SNAME" + index, npwp.getF1cname());
            reqBuilder.addPart("SNAME" + index, new StringBody(npwp.getF1cname(), ContentType.TEXT_PLAIN));
            multipart.addFormField("SGRXMLID" + index, npwp.getF1cparentId());
            reqBuilder.addPart("SGRXMLID" + index,
                    new StringBody(npwp.getF1cparentId(), ContentType.TEXT_PLAIN));

            boolean error_file_operation = false, uploadFiles = true;
            long sectFilesSize = 0;
            boolean tooLargeDsc = false, tooLargeGb = false, tooLargeDoc = false;

            ArrayList<String> dscFiles = new ArrayList<String>();

            try {
                if (!npwp.getBxDescriptsJson().equals(npwp.getF1cDescriptsJson())) {
                    //logStr+="["+npwp.getF1cDescriptsJson()+"]";
                    JsonReader jsonReader = Json.createReader(new StringReader(npwp.getF1cDescriptsJson()));
                    JsonObject jo = jsonReader.readObject();

                    int dcount = 0;
                    logStr += "cnt=" + jo.getString("dc", "0");
                    for (int i = 0; i < Tools.parseInt(jo.getString("dc", "0"), 0); i++) {
                        logStr += ("[" + i + "]");
                        try {
                            if (jo.getString("fp" + i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + jo.getString("fp" + i).replace("\\", "/"));
                                if (f.length() <= maxPostedFileSize
                                        && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) {
                                    dscFiles.add(jo.getString("fp" + i).replace("\\", "/"));
                                    multipart.addFormField("FDSC" + index + "DSC" + dcount,
                                            jo.getString("dsc" + i));
                                    multipart.addFormField("FDSC" + index + "FN" + dcount,
                                            jo.getString("fn" + i));
                                    reqBuilder.addPart("FDSC" + index + "DSC" + dcount,
                                            new StringBody(jo.getString("dsc" + i), ContentType.TEXT_PLAIN));
                                    reqBuilder.addPart("FDSC" + index + "FN" + dcount,
                                            new StringBody(jo.getString("fn" + i), ContentType.TEXT_PLAIN));
                                    sectFilesSize += f.length();
                                    dcount++;
                                } else {
                                    tooLargeDsc = true;
                                    logStr += "Too large " + jo.getString("fp" + i);
                                }
                            }

                        } catch (Exception fle) {
                            //sectFilesSize=0;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error dsc file operation!!! " + fle);
                        }

                    }

                    if (dcount > 0) {
                        multipart.addFormField("FDSCDC" + index, "" + dcount);
                        reqBuilder.addPart("FDSCDC" + index,
                                new StringBody("" + dcount, ContentType.TEXT_PLAIN));
                    }

                }
            } catch (Exception fle) {
                logStr += (npwp.getF1cname() + " Error F1cDescriptsJson parse operation!!! " + fle + "[["
                        + npwp.getF1cDescriptsJson() + "]]");
            }

            ArrayList<String> gbFiles = new ArrayList<String>();

            try {
                if (!npwp.getBxGabaritsJson().equals(npwp.getF1cGabaritsJson())) {
                    //logStr+="["+npwp.getF1cGabaritsJson()+"]";
                    JsonReader jsonReader = Json.createReader(new StringReader(npwp.getF1cGabaritsJson()));
                    JsonObject jo = jsonReader.readObject();

                    int dcount = 0;
                    logStr += "cnt=" + jo.getString("dc", "0");
                    for (int i = 0; i < Tools.parseInt(jo.getString("dc", "0"), 0); i++) {
                        logStr += ("[" + i + "]");
                        try {
                            if (jo.getString("fp" + i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + jo.getString("fp" + i).replace("\\", "/"));
                                if (f.length() <= maxPostedFileSize
                                        && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) {
                                    gbFiles.add(jo.getString("fp" + i).replace("\\", "/"));
                                    multipart.addFormField("FGB" + index + "DSC" + dcount,
                                            jo.getString("dsc" + i));
                                    multipart.addFormField("FGB" + index + "FN" + dcount,
                                            jo.getString("fn" + i));
                                    reqBuilder.addPart("FGB" + index + "DSC" + dcount,
                                            new StringBody(jo.getString("dsc" + i), ContentType.TEXT_PLAIN));
                                    reqBuilder.addPart("FGB" + index + "FN" + dcount,
                                            new StringBody(jo.getString("fn" + i), ContentType.TEXT_PLAIN));
                                    sectFilesSize += f.length();
                                    dcount++;
                                    logStr += "[=" + dcount + "=]";
                                } else {
                                    tooLargeGb = true;
                                    logStr += "Too large " + jo.getString("fp" + i);
                                }
                            }

                        } catch (Exception fle) {
                            //sectFilesSize=0;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error dsc file operation!!! " + fle);
                        }

                    }

                    if (dcount > 0) {
                        multipart.addFormField("FGBDC" + index, "" + dcount);
                        reqBuilder.addPart("FGBDC" + index,
                                new StringBody("" + dcount, ContentType.TEXT_PLAIN));
                    }

                }
            } catch (Exception fle) {
                logStr += (npwp.getF1cname() + " Error F1cGabaritsJson parse operation!!! " + fle + "[["
                        + npwp.getF1cGabaritsJson() + "]]");
            }

            ArrayList<String> docFiles = new ArrayList<String>();

            try {
                if (!npwp.getBxDocsJson().equals(npwp.getF1cDocsJson())) {
                    //logStr+="["+npwp.getF1cDocsJson()+"]";
                    JsonReader jsonReader = Json.createReader(new StringReader(npwp.getF1cDocsJson()));
                    JsonObject jo = jsonReader.readObject();

                    int dcount = 0;
                    logStr += "cnt=" + jo.getString("dc", "0");
                    for (int i = 0; i < Tools.parseInt(jo.getString("dc", "0"), 0); i++) {
                        logStr += ("[" + i + "]");
                        try {
                            if (jo.getString("fp" + i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + jo.getString("fp" + i).replace("\\", "/"));
                                if (f.length() <= maxPostedDocFileSize
                                        && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) {
                                    docFiles.add(jo.getString("fp" + i).replace("\\", "/"));
                                    multipart.addFormField("FDOC" + index + "DSC" + dcount,
                                            jo.getString("dsc" + i));
                                    //logStr+=("FDOC"+index+"FN+"+dcount+"="+jo.getString("fn"+i));
                                    multipart.addFormField("FDOC" + index + "FN" + dcount,
                                            jo.getString("fn" + i));
                                    reqBuilder.addPart("FDOC" + index + "DSC" + dcount,
                                            new StringBody(jo.getString("dsc" + i), ContentType.TEXT_PLAIN));
                                    reqBuilder.addPart("FDOC" + index + "FN" + dcount,
                                            new StringBody(StringEscapeUtils.escapeJava(jo.getString("fn" + i)),
                                                    ContentType.TEXT_PLAIN));
                                    sectFilesSize += f.length();
                                    dcount++;
                                } else {
                                    tooLargeDoc = true;
                                    logStr += "Too large " + jo.getString("fp" + i);
                                }
                            }

                        } catch (Exception fle) {
                            //sectFilesSize=0;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error doc file operation!!! " + fle);
                        }

                    }

                    if (dcount > 0) {
                        multipart.addFormField("FDOCDC" + index, "" + dcount);
                        reqBuilder.addPart("FDOCDC" + index,
                                new StringBody("" + dcount, ContentType.TEXT_PLAIN));
                    }

                }
            } catch (Exception fle) {
                logStr += (npwp.getF1cname() + " Error F1cDocsJson parse operation!!! " + fle + "[["
                        + npwp.getF1cDocsJson() + "]]");
            }

            try {
                if (npwp.getF1cPicture().length() > 0 && npwp.getBxPicture().length() == 0 && uploadFiles) {
                    File f = new File(mountImgPath + npwp.getF1cPicture().replace("\\", "/"));
                    if (f.length() <= maxPostedFileSize
                            && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) {
                        sectFilesSize += f.length();
                    }
                }
            } catch (Exception fle) {
                //sectFilesSize=0;
                error_file_operation = true;
                logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cPicture file operation!!! " + fle);
            }

            try {

                if (npwp.getF1cMcatalog().length() > 0 && npwp.getBxMcatalog().length() == 0 && uploadFiles) {
                    File f = new File(mountImgPath + npwp.getF1cMcatalog().replace("\\", "/"));
                    if (f.length() <= maxPostedDocFileSize
                            && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) {
                        sectFilesSize += f.length();
                    }
                }

            } catch (Exception fle) {
                //sectFilesSize=0;
                error_file_operation = true;
                logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cMcatalog file operation!!! " + fle);
            }

            if ((allFileSize + sectFilesSize) > maxPostFilePartSize) {
                logStr += ("NAME " + npwp.getF1cname() + " - too big sect files sizes summ!!!");
                //continue; 
            } else {
                if (!error_file_operation) {
                    try {
                        if (!npwp.getF1cPicture().equals(npwp.getBxPicture()) && uploadFiles) {
                            File f = new File(mountImgPath + npwp.getF1cPicture().replace("\\", "/"));
                            if (f.length() <= maxPostedFileSize
                                    && ((allFileSize + f.length()) < maxPostFilePartSize)) {
                                logStr += ",getF1cPicture " + npwp.getF1cPicture() + "fname=" + f.getName()
                                        + ",fpath=" + f.getPath() + ",flength=[" + f.length() + "]";
                                allFileSize += f.length();

                                try {
                                    BufferedImage originalImage = ImageIO.read(f);
                                    if ((originalImage.getHeight() > 400 || originalImage.getWidth() > 400)
                                            && false) {
                                        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
                                                : originalImage.getType();
                                        BufferedImage resizeImageJpg = resizeImage(originalImage, type);

                                        logStr += "Not require resize";
                                        //multipart.addFilePart("PICTURE"+index, (resizeImageJpg) );
                                        //multipart.addFormField("SETPICTURE"+index, "1");
                                    } else {
                                        logStr += "Not require resize";
                                        multipart.addFilePart("PICTURE" + index, (f));
                                        multipart.addFormField("SETPICTURE" + index, "1");
                                        multipart.addFormField("PICTURE_PATH" + index,
                                                StringEscapeUtils.escapeJava(npwp.getF1cPicture()));
                                        reqBuilder.addPart("PICTURE" + index, new FileBody(f));
                                        reqBuilder.addPart("SETPICTURE" + index,
                                                new StringBody("1", ContentType.TEXT_PLAIN));
                                    }
                                } catch (Exception frle) {
                                    logStr += "Error resizing" + frle;
                                    multipart.addFilePart("PICTURE" + index, (f));
                                    multipart.addFormField("SETPICTURE" + index, "1");
                                    multipart.addFormField("PICTURE_PATH" + index,
                                            StringEscapeUtils.escapeJava(npwp.getF1cPicture()));
                                    reqBuilder.addPart("PICTURE" + index, new FileBody(f));
                                    reqBuilder.addPart("SETPICTURE" + index,
                                            new StringBody("1", ContentType.TEXT_PLAIN));
                                }
                            } else {
                                multipart.addFormField("SETPICTURE" + index, "0");
                                reqBuilder.addPart("SETPICTURE" + index,
                                        new StringBody("0", ContentType.TEXT_PLAIN));
                                logStr += ",getF1cPicture " + f.length() + " more "
                                        + maxPostedFileSize / 1000000 + "Mbytes or too big allFileSize";
                            }
                        }
                    } catch (Exception fle) {
                        error_file_operation = true;
                        logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cPicture file operation!!! "
                                + fle);
                    }
                    try {
                        if (npwp.getF1cMcatalog().length() > 0 && npwp.getBxMcatalog().length() == 0
                                && uploadFiles) {
                            File f = new File(mountImgPath + npwp.getF1cMcatalog().replace("\\", "/"));
                            if (f.length() <= maxPostedDocFileSize
                                    && ((allFileSize + f.length()) < maxPostFilePartSize)) {
                                logStr += ",getF1cMcatalog " + npwp.getF1cMcatalog();
                                allFileSize += f.length();
                                multipart.addFilePart("MASTER_CATALOG" + index, (f));
                                multipart.addFormField("SETMASTER_CATALOG" + index, "1");
                                reqBuilder.addPart("MASTER_CATALOG" + index, new FileBody(f));
                                reqBuilder.addPart("SETMASTER_CATALOG" + index,
                                        new StringBody("1", ContentType.TEXT_PLAIN));
                            } else {
                                multipart.addFormField("SETMASTER_CATALOG" + index, "0");
                                reqBuilder.addPart("SETMASTER_CATALOG" + index,
                                        new StringBody("0", ContentType.TEXT_PLAIN));
                                logStr += ",getF1cMcatalog " + f.length() + " more "
                                        + maxPostedDocFileSize / 1000000 + "Mbytes or too big allFileSize";
                            }
                        }
                    } catch (Exception fle) {
                        error_file_operation = true;
                        logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cMcatalog file operation!!! "
                                + fle);
                    }

                    int succFilesCount = 0;
                    for (int i = 0; i < dscFiles.size(); i++) {
                        try {
                            if (dscFiles.get(i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + dscFiles.get(i));
                                long lastFSize = 0;
                                lastFSize = f.length();
                                if (lastFSize <= maxPostedFileSize
                                        && ((allFileSize + lastFSize) < maxPostFilePartSize)) {
                                    logStr += ",dscFiles " + dscFiles.get(i);
                                    multipart.addFilePart("FDSC" + index + "FP" + i, (f));
                                    multipart.addFormField("FDSC" + index + "FPSET" + i, "1");
                                    reqBuilder.addPart("FDSC" + index + "FP" + i, new FileBody(f));
                                    reqBuilder.addPart("FDSC" + index + "FPSET" + i,
                                            new StringBody("1", ContentType.TEXT_PLAIN));
                                    succFilesCount++;
                                    allFileSize += lastFSize;
                                } else {
                                    //if(lastFSize>maxPostedFileSize)
                                    //    succFilesCount++;
                                    tooLargeDsc = true;
                                    multipart.addFormField("FDSC" + index + "FPSET" + i, "0");
                                    reqBuilder.addPart("FDSC" + index + "FPSET" + i,
                                            new StringBody("0", ContentType.TEXT_PLAIN));
                                    logStr += ",dscFiles " + f.length() + " more " + maxPostedFileSize / 1000000
                                            + "Mbytes or too big allFileSize";
                                }
                            }
                        } catch (Exception fle) {
                            tooLargeDsc = true;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error dscFiles file operation!!! "
                                    + fle);
                        }

                    }

                    if (!tooLargeDsc) {
                        if ((dscFiles.size() <= 0)
                                || ((succFilesCount >= 1) && (succFilesCount >= (int) (dscFiles.size() / 2)))) {
                            if (!npwp.getBxDescriptsJson().equals(npwp.getF1cDescriptsJson())) {
                                multipart.addFormField("SETDESCRIPTS_JSON" + index, "1");
                                reqBuilder.addPart("SETDESCRIPTS_JSON" + index,
                                        new StringBody("1", ContentType.TEXT_PLAIN));
                            } else {
                                multipart.addFormField("SETDESCRIPTS_JSON" + index, "0");
                                reqBuilder.addPart("SETDESCRIPTS_JSON" + index,
                                        new StringBody("0", ContentType.TEXT_PLAIN));
                            }
                            multipart.addFormField("DESCRIPTS_JSON" + index,
                                    StringEscapeUtils.escapeJava(npwp.getF1cDescriptsJson()));
                            reqBuilder.addPart("DESCRIPTS_JSON" + index,
                                    new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cDescriptsJson()),
                                            ContentType.TEXT_PLAIN));
                        } else
                            logStr += ("NAME " + npwp.getF1cname() + " - Error dscFiles count!!! ");
                    }

                    succFilesCount = 0;
                    for (int i = 0; i < gbFiles.size(); i++) {
                        try {
                            if (gbFiles.get(i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + gbFiles.get(i));
                                long lastFSize = 0;
                                lastFSize = f.length();
                                if (lastFSize <= maxPostedFileSize
                                        && ((allFileSize + lastFSize) < maxPostFilePartSize)) {
                                    logStr += ",gbFiles " + gbFiles.get(i);
                                    multipart.addFilePart("FGB" + index + "FP" + i, (f));
                                    multipart.addFormField("FGB" + index + "FPSET" + i, "1");
                                    reqBuilder.addPart("FGB" + index + "FP" + i, new FileBody(f));
                                    reqBuilder.addPart("FGB" + index + "FPSET" + i,
                                            new StringBody("1", ContentType.TEXT_PLAIN));
                                    succFilesCount++;
                                    allFileSize += lastFSize;
                                } else {
                                    //if(lastFSize>maxPostedFileSize)
                                    //    succFilesCount++;
                                    tooLargeGb = true;
                                    multipart.addFormField("FGB" + index + "FPSET" + i, "0");
                                    reqBuilder.addPart("FGB" + index + "FPSET" + i,
                                            new StringBody("0", ContentType.TEXT_PLAIN));
                                    logStr += ",gbFiles " + f.length() + " more " + maxPostedFileSize / 1000000
                                            + "Mbytes or too big allFileSize";
                                }
                            }
                        } catch (Exception fle) {
                            tooLargeGb = true;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error gbrFiles file operation!!! "
                                    + fle);
                        }

                    }

                    if (!tooLargeGb) {
                        if ((gbFiles.size() <= 0)
                                || ((succFilesCount >= 1) && (succFilesCount >= (int) (gbFiles.size() / 2)))) {
                            if (!npwp.getBxGabaritsJson().equals(npwp.getF1cGabaritsJson())) {
                                multipart.addFormField("SETGABARITS_JSON" + index, "1");
                                reqBuilder.addPart("SETGABARITS_JSON" + index,
                                        new StringBody("1", ContentType.TEXT_PLAIN));
                            } else {
                                multipart.addFormField("SETGABARITS_JSON" + index, "0");
                                reqBuilder.addPart("SETGABARITS_JSON" + index,
                                        new StringBody("0", ContentType.TEXT_PLAIN));
                            }
                            multipart.addFormField("GABARITS_JSON" + index,
                                    StringEscapeUtils.escapeJava(npwp.getF1cGabaritsJson()));
                            reqBuilder.addPart("GABARITS_JSON" + index,
                                    new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cGabaritsJson()),
                                            ContentType.TEXT_PLAIN));
                        } else
                            logStr += ("NAME " + npwp.getF1cname() + " - Error gbrFiles count!!! ");
                    }

                    succFilesCount = 0;
                    for (int i = 0; i < docFiles.size(); i++) {
                        try {
                            if (docFiles.get(i).length() > 0 && uploadFiles) {
                                File f = new File(mountImgPath + docFiles.get(i));
                                long lastFSize = 0;
                                lastFSize = f.length();
                                if (lastFSize <= maxPostedDocFileSize
                                        && ((allFileSize + lastFSize) < maxPostFilePartSize)) {
                                    logStr += ",docFiles " + docFiles.get(i);
                                    multipart.addFilePart("FDOC" + index + "FP" + i, (f));
                                    multipart.addFormField("FDOC" + index + "FPSET" + i, "1");
                                    reqBuilder.addPart("FDOC" + index + "FP" + i, new FileBody(f));
                                    reqBuilder.addPart("FDOC" + index + "FPSET" + i,
                                            new StringBody("1", ContentType.TEXT_PLAIN));
                                    succFilesCount++;
                                    allFileSize += lastFSize;
                                } else {
                                    //if(lastFSize>maxPostedFileSize)
                                    //    succFilesCount++;
                                    tooLargeDoc = true;
                                    multipart.addFormField("FDOC" + index + "FPSET" + i, "0");
                                    reqBuilder.addPart("FDOC" + index + "FPSET" + i,
                                            new StringBody("0", ContentType.TEXT_PLAIN));
                                    logStr += ",docFiles " + f.length() + " more "
                                            + maxPostedDocFileSize / 1000000 + "Mbytes or too big allFileSize";
                                }
                            }
                        } catch (Exception fle) {
                            tooLargeDoc = true;
                            error_file_operation = true;
                            logStr += ("NAME " + npwp.getF1cname() + " - Error docFiles file operation!!! "
                                    + fle);
                        }

                    }

                    if (!tooLargeDoc) {
                        if ((docFiles.size() <= 0)
                                || ((succFilesCount >= 1) && (succFilesCount >= (int) (docFiles.size() / 2)))) {
                            if (!npwp.getBxDocsJson().equals(npwp.getF1cDocsJson())) {
                                multipart.addFormField("SETDOCS_JSON" + index, "1");
                                reqBuilder.addPart("SETDOCS_JSON" + index,
                                        new StringBody("1", ContentType.TEXT_PLAIN));
                            } else {
                                multipart.addFormField("SETDOCS_JSON" + index, "0");
                                reqBuilder.addPart("SETDOCS_JSON" + index,
                                        new StringBody("0", ContentType.TEXT_PLAIN));
                            }
                            multipart.addFormField("DOCS_JSON" + index,
                                    StringEscapeUtils.escapeJava(npwp.getF1cDocsJson()));
                            reqBuilder.addPart("DOCS_JSON" + index,
                                    new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cDocsJson()),
                                            ContentType.TEXT_PLAIN));
                        } else
                            logStr += ("NAME " + npwp.getF1cname() + " - Error docFiles count!!! ");
                    }

                }
            }

            if (npwp.getBxSortOrder() != npwp.getF1cSortOrder()) {
                multipart.addFormField("SETSORT_ORDER" + index, "1");
                reqBuilder.addPart("SETSORT_ORDER" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSORT_ORDER" + index, "0");
                reqBuilder.addPart("SETSORT_ORDER" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SORT_ORDER" + index, "" + npwp.getF1cSortOrder());
            reqBuilder.addPart("SORT_ORDER" + index,
                    new StringBody("" + npwp.getF1cSortOrder(), ContentType.TEXT_PLAIN));

            if (!npwp.getBxDescription().equals(npwp.getF1cDescription())) {
                multipart.addFormField("SETDESCRIPTION" + index, "1");
                reqBuilder.addPart("SETDESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETDESCRIPTION" + index, "0");
                reqBuilder.addPart("SETDESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("DESCRIPTION" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cDescription()));
            reqBuilder.addPart("DESCRIPTION" + index,
                    new StringBody("" + npwp.getF1cSortOrder(), ContentType.TEXT_PLAIN));

            if (!npwp.getBxFullDescription().equals(npwp.getF1cFullDescription())) {
                multipart.addFormField("SETFULL_DESCRIPTION" + index, "1");
                reqBuilder.addPart("SETFULL_DESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETFULL_DESCRIPTION" + index, "0");
                reqBuilder.addPart("SETFULL_DESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("FULL_DESCRIPTION" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cFullDescription()));
            reqBuilder.addPart("FULL_DESCRIPTION" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cFullDescription()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxTypeCompleting().equals(npwp.getF1cTypeCompleting())) {
                multipart.addFormField("SETTYPE_COMPLETING" + index, "1");
                reqBuilder.addPart("SETTYPE_COMPLETING" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETTYPE_COMPLETING" + index, "0");
                reqBuilder.addPart("SETTYPE_COMPLETING" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("TYPE_COMPLETING" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cTypeCompleting()));
            reqBuilder.addPart("TYPE_COMPLETING" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cTypeCompleting()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxCharGabarits().equals(npwp.getF1cCharGabarits())) {
                multipart.addFormField("SETCHAR_GABARITS" + index, "1");
                reqBuilder.addPart("SETCHAR_GABARITS" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETCHAR_GABARITS" + index, "0");
                reqBuilder.addPart("SETCHAR_GABARITS" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("CHAR_GABARITS" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cCharGabarits()));
            reqBuilder.addPart("CHAR_GABARITS" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cCharGabarits()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxShortDescription().equals(npwp.getF1cShortDescription())) {
                multipart.addFormField("SETSHORT_DESCRIPTION" + index, "1");
                reqBuilder.addPart("SETSHORT_DESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSHORT_DESCRIPTION" + index, "0");
                reqBuilder.addPart("SETSHORT_DESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SHORT_DESCRIPTION" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cShortDescription()));
            reqBuilder.addPart("SHORT_DESCRIPTION" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cShortDescription()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxDocumentation().equals(npwp.getF1cDocumentation())) {
                multipart.addFormField("SETDOCUMENTATION" + index, "1");
                reqBuilder.addPart("SETDOCUMENTATION" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETDOCUMENTATION" + index, "0");
                reqBuilder.addPart("SETDOCUMENTATION" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("DOCUMENTATION" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cDocumentation()));
            reqBuilder.addPart("DOCUMENTATION" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cDocumentation()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxVideoDescription().equals(npwp.getF1cVideoDescription())) {
                multipart.addFormField("SETVIDEO_DESCRIPTION" + index, "1");
                reqBuilder.addPart("SETVIDEO_DESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETVIDEO_DESCRIPTION" + index, "0");
                reqBuilder.addPart("SETVIDEO_DESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("VIDEO_DESCRIPTION" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cVideoDescription()));
            reqBuilder.addPart("VIDEO_DESCRIPTION" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cVideoDescription()), ContentType.TEXT_PLAIN));

            if (npwp.getBxCollapsevc() != npwp.getF1cCollapsevc()) {
                multipart.addFormField("SETCOLLAPSEVC" + index, "1");
                reqBuilder.addPart("SETCOLLAPSEVC" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETCOLLAPSEVC" + index, "0");
                reqBuilder.addPart("SETCOLLAPSEVC" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("COLLAPSEVC" + index,
                    StringEscapeUtils.escapeJava("" + npwp.getF1cCollapsevc()));
            reqBuilder.addPart("COLLAPSEVC" + index, new StringBody(
                    StringEscapeUtils.escapeJava("" + npwp.getF1cCollapsevc()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxAdvants().equals(npwp.getF1cAdvants())) {
                multipart.addFormField("SETADVANTS" + index, "1");
                reqBuilder.addPart("SETADVANTS" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETADVANTS" + index, "0");
                reqBuilder.addPart("SETADVANTS" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("ADVANTS" + index, StringEscapeUtils.escapeJava(npwp.getF1cAdvants()));
            reqBuilder.addPart("ADVANTS" + index,
                    new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cAdvants()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxFilterProps().equals(npwp.getF1cFilterProps())) {
                multipart.addFormField("SETFILTER_PROPS" + index, "1");
                reqBuilder.addPart("SETFILTER_PROPS" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETFILTER_PROPS" + index, "0");
                reqBuilder.addPart("SETFILTER_PROPS" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("FILTER_PROPS" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cFilterProps()));
            reqBuilder.addPart("FILTER_PROPS" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cFilterProps()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxSeoAliasUrl().equals(npwp.getF1cSeoAliasUrl())
                    && npwp.getF1cSeoAliasUrl().length() > 3) {
                multipart.addFormField("SETSEO_ALIAS_URL" + index, "1");
                reqBuilder.addPart("SETSEO_ALIAS_URL" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSEO_ALIAS_URL" + index, "0");
                reqBuilder.addPart("SETSEO_ALIAS_URL" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SEO_ALIAS_URL" + index,
                    StringEscapeUtils.escapeJava(npwp.getF1cSeoAliasUrl()));
            reqBuilder.addPart("SEO_ALIAS_URL" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cSeoAliasUrl()), ContentType.TEXT_PLAIN));

            if (npwp.getBxSeoAliasUrl().length() <= 0 && npwp.getF1cSeoAliasUrl().length() <= 3
                    && npwp.getF1cname().length() > 0) {
                multipart.addFormField("SETSEO_ALIAS_URL_FROM_NAME" + index, "1");
                multipart.addFormField("SEO_ALIAS_URL_FROM_NAME" + index,
                        StringEscapeUtils.escapeJava(npwp.getF1cname()));
                reqBuilder.addPart("SETSEO_ALIAS_URL_FROM_NAME" + index,
                        new StringBody("1", ContentType.TEXT_PLAIN));
                reqBuilder.addPart("SEO_ALIAS_URL_FROM_NAME" + index, new StringBody(
                        StringEscapeUtils.escapeJava(npwp.getF1cname()), ContentType.TEXT_PLAIN));
            }

            if (!npwp.getBxSeoTitle().equals(npwp.getF1cSeoTitle())) {
                multipart.addFormField("SETSEO_TITLE" + index, "1");
                reqBuilder.addPart("SETSEO_TITLE" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSEO_TITLE" + index, "0");
                reqBuilder.addPart("SETSEO_TITLE" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SEO_TITLE" + index, StringEscapeUtils.escapeJava(npwp.getF1cSeoTitle()));
            reqBuilder.addPart("SEO_TITLE" + index, new StringBody(
                    StringEscapeUtils.escapeJava(npwp.getF1cSeoTitle()), ContentType.TEXT_PLAIN));

            if (!npwp.getBxSeoH1().equals(npwp.getF1cSeoH1())) {
                multipart.addFormField("SETSEO_H1" + index, "1");
                reqBuilder.addPart("SETSEO_H1" + index, new StringBody("1", ContentType.TEXT_PLAIN));
            } else {
                multipart.addFormField("SETSEO_H1" + index, "0");
                reqBuilder.addPart("SETSEO_H1" + index, new StringBody("0", ContentType.TEXT_PLAIN));
            }
            multipart.addFormField("SEO_H1" + index, StringEscapeUtils.escapeJava(npwp.getF1cSeoH1()));
            reqBuilder.addPart("SEO_H1" + index,
                    new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cSeoH1()), ContentType.TEXT_PLAIN));

            index++;
        }

        try {
            if (logStr.length() > 0)
                cbLogsFacade.insertLog("INFO", "UPD SECT TO SEND ",
                        "<p style=\"font-size:10px !important;\">" + logStr + "</p>");
        } catch (Exception lgen) {
        }

        List<String> response = multipart.finish();

        for (String line : response) {
            sreply = sreply + line;
        }

        /*sreply = "{}";
                
        HttpEntity reqEntity = reqBuilder.build();
        httppost.setEntity(reqEntity);
                
        //System.out.println("executing request " + httppost.getRequestLine());
        try {
        CloseableHttpResponse clresponse = httpclient.execute(httppost);
        try {
            //System.out.println("----------------------------------------");
            //clresponse.getStatusLine();
            HttpEntity resEntity = clresponse.getEntity();
            if (resEntity != null) {
                //System.out.println("Response content length: " + resEntity.getContentLength());
                //resEntity.getContent(); resEntity.getContentEncoding()
                try {
                    String responseString = EntityUtils.toString(resEntity, "UTF-8");
                    sreply = responseString;
                    EntityUtils.consume(resEntity);
                } catch(Exception ee)   {
                            
                }
            }
                    
        } finally {
            try {
                clresponse.close();
            } catch(Exception ee)   {
                
            }
        }
        } catch(Exception ee)   {
                    
        }*/

        try {
            JsonReader jsonReader = Json.createReader(new StringReader(sreply));
            JsonObject jobject = jsonReader.readObject();
            try {
                cbLogsFacade.insertLog("INFO", "SUCCESS OF PARSE SERVER REPLY",
                        "SUCCESS OF PARSE SERVER REPLY=" + jobject.toString());
            } catch (Exception lge) {

            }
            try {
                if (jobject.getString("critical_info", "").length() > 0)
                    cbLogsFacade.insertLog("CRITICAL_INFO", "SERVER REPLY DETAIL",
                            jobject.getString("critical_info", ""));
            } catch (Exception lge) {

            }
            try {
                if (jobject.getString("critical_errs", "").length() > 0)
                    cbLogsFacade.insertLog("CRITICAL_ERRS", "SERVER REPLY DETAIL",
                            jobject.getString("critical_errs", ""));
            } catch (Exception lge) {

            }
        } catch (Exception pe) {
            try {
                cbLogsFacade.insertLog("ERROR", "ERROR OF PARSE SERVER REPLY",
                        "ERROR OF PARSE SERVER REPLY" + sreply);
            } catch (Exception lge) {

            }
        }

    } catch (Exception ex) {
        try {
            cbLogsFacade.insertLog("ERROR", "ERROR of postMultipartSectUpd",
                    logStr + " ERROR of postMultipartSectUpd " + ex);
        } catch (Exception lge) {

        }
    }

    return reply;
}

From source file:org.ednovo.gooru.application.server.service.uploadServlet.java

public String fileUpload(byte[] bytes, String data, String fileName, Long fileSize, String urlVal)
        throws Exception {
    String ret = "";
    logger.info("upload Url:::" + urlVal);
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost httppost = new HttpPost(urlVal);
    MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
    ByteArrayBody bab = new ByteArrayBody(bytes, fileName);
    reqEntity.addPart("image", bab);
    httppost.setEntity(reqEntity.build());
    HttpResponse response = httpClient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    if (resEntity != null) {
        ret = EntityUtils.toString(resEntity);
    }//from  w  w  w . j  ava 2  s  . co m
    logger.info("upload response:::" + ret);
    return ret;
}

From source file:org.opendatakit.briefcase.util.AggregateUtils.java

public static final boolean uploadFilesToServer(ServerConnectionInfo serverInfo, URI u,
        String distinguishedFileTagName, File file, List<File> files, DocumentDescription description,
        SubmissionResponseAction action, TerminationFuture terminationFuture, FormStatus formToTransfer) {

    boolean allSuccessful = true;
    formToTransfer.setStatusString("Preparing for upload of " + description.getDocumentDescriptionType()
            + " with " + files.size() + " media attachments", true);
    EventBus.publish(new FormStatusEvent(formToTransfer));

    boolean first = true; // handles case where there are no media files
    int lastJ = 0;
    int j = 0;//from ww w.  ja v  a2  s. c  o  m
    while (j < files.size() || first) {
        lastJ = j;
        first = false;

        if (terminationFuture.isCancelled()) {
            formToTransfer.setStatusString("Aborting upload of " + description.getDocumentDescriptionType()
                    + " with " + files.size() + " media attachments", true);
            EventBus.publish(new FormStatusEvent(formToTransfer));
            return false;
        }

        HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);

        long byteCount = 0L;

        // mime post
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        // add the submission file first...
        FileBody fb = new FileBody(file, ContentType.TEXT_XML);
        builder.addPart(distinguishedFileTagName, fb);
        log.info("added " + distinguishedFileTagName + ": " + file.getName());
        byteCount += file.length();

        for (; j < files.size(); j++) {
            File f = files.get(j);
            String fileName = f.getName();
            int idx = fileName.lastIndexOf(".");
            String extension = "";
            if (idx != -1) {
                extension = fileName.substring(idx + 1);
            }

            // we will be processing every one of these, so
            // we only need to deal with the content type determination...
            if (extension.equals("xml")) {
                fb = new FileBody(f, ContentType.TEXT_XML);
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added xml file " + f.getName());
            } else if (extension.equals("jpg")) {
                fb = new FileBody(f, ContentType.create("image/jpeg"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added image file " + f.getName());
            } else if (extension.equals("3gpp")) {
                fb = new FileBody(f, ContentType.create("audio/3gpp"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added audio file " + f.getName());
            } else if (extension.equals("3gp")) {
                fb = new FileBody(f, ContentType.create("video/3gpp"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added video file " + f.getName());
            } else if (extension.equals("mp4")) {
                fb = new FileBody(f, ContentType.create("video/mp4"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added video file " + f.getName());
            } else if (extension.equals("csv")) {
                fb = new FileBody(f, ContentType.create("text/csv"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added csv file " + f.getName());
            } else if (extension.equals("xls")) {
                fb = new FileBody(f, ContentType.create("application/vnd.ms-excel"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added xls file " + f.getName());
            } else {
                fb = new FileBody(f, ContentType.create("application/octet-stream"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.warn("added unrecognized file (application/octet-stream) " + f.getName());
            }

            // we've added at least one attachment to the request...
            if (j + 1 < files.size()) {
                if ((j - lastJ + 1) > 100 || byteCount + files.get(j + 1).length() > 10000000L) {
                    // more than 100 attachments or the next file would exceed the 10MB threshold...
                    log.info("Extremely long post is being split into multiple posts");
                    try {
                        StringBody sb = new StringBody("yes",
                                ContentType.DEFAULT_TEXT.withCharset(Charset.forName("UTF-8")));
                        builder.addPart("*isIncomplete*", sb);
                    } catch (Exception e) {
                        log.error("impossible condition", e);
                        throw new IllegalStateException("never happens");
                    }
                    ++j; // advance over the last attachment added...
                    break;
                }
            }
        }

        httppost.setEntity(builder.build());

        int[] validStatusList = { 201 };

        try {
            if (j != files.size()) {
                formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType()
                        + " and media files " + (lastJ + 1) + " through " + (j + 1) + " of " + files.size()
                        + " media attachments", true);
            } else if (j == 0) {
                formToTransfer.setStatusString(
                        "Uploading " + description.getDocumentDescriptionType() + " with no media attachments",
                        true);
            } else {
                formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and "
                        + (j - lastJ) + ((lastJ != 0) ? " remaining" : "") + " media attachments", true);
            }
            EventBus.publish(new FormStatusEvent(formToTransfer));

            httpRetrieveXmlDocument(httppost, validStatusList, serverInfo, false, description, action);
        } catch (XmlDocumentFetchException e) {
            allSuccessful = false;
            log.error("upload failed", e);
            formToTransfer.setStatusString("UPLOAD FAILED: " + e.getMessage(), false);
            EventBus.publish(new FormStatusEvent(formToTransfer));

            if (description.isCancelled())
                return false;
        }
    }

    return allSuccessful;
}