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

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

Introduction

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

Prototype

public HttpEntity build() 

Source Link

Usage

From source file:com.scoopit.weedfs.client.WeedFSClientImpl.java

private int write(WeedFSFile file, Location location, File fileToUpload, byte[] dataToUpload,
        InputStream inputToUpload, String fileName) throws IOException, WeedFSException {
    StringBuilder url = new StringBuilder();
    if (!location.publicUrl.contains("http")) {
        url.append("http://");
    }//from w  w  w  .  j a  v  a  2s.  c  om
    url.append(location.publicUrl);
    url.append('/');
    url.append(file.fid);

    if (file.version > 0) {
        url.append('_');
        url.append(file.version);
    }

    HttpPost post = new HttpPost(url.toString());

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    if (fileToUpload != null) {
        if (fileName == null) {
            fileName = fileToUpload.getName();
        }
        multipartEntityBuilder.addBinaryBody("file", fileToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    } else if (dataToUpload != null) {
        multipartEntityBuilder.addBinaryBody("file", dataToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    } else {
        multipartEntityBuilder.addBinaryBody("file", inputToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    }
    post.setEntity(multipartEntityBuilder.build());

    try {
        HttpResponse response = httpClient.execute(post);

        String content = getContentOrNull(response);
        ObjectMapper mapper = new ObjectMapper();
        try {
            WriteResult result = mapper.readValue(content, WriteResult.class);

            if (result.error != null) {
                throw new WeedFSException(result.error);
            }

            return result.size;
        } catch (JsonMappingException | JsonParseException e) {
            throw new WeedFSException("Unable to parse JSON from weed-fs from: " + content, e);
        }
    } finally {
        post.abort();
    }
}

From source file:com.adobe.ags.curly.controller.ActionRunner.java

private void addPostParams(HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException {
    final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
    List<NameValuePair> formParams = new ArrayList<>();
    postVariables.forEach((name, values) -> values.forEach(value -> {
        if (multipart) {
            if (value.startsWith("@")) {
                File f = new File(value.substring(1));
                multipartBuilder.addBinaryBody(name, f, ContentType.DEFAULT_BINARY, f.getName());
            } else {
                multipartBuilder.addTextBody(name, value);
            }//from  w w  w .  j  a v  a2  s. co m
        } else {
            formParams.add(new BasicNameValuePair(name, value));
        }
    }));
    if (multipart) {
        request.setEntity(multipartBuilder.build());
    } else {
        request.setEntity(new UrlEncodedFormEntity(formParams));
    }
}

From source file:org.apache.sling.testing.clients.osgi.OsgiConsoleClient.java

/**
 * Install a bundle using the Felix webconsole HTTP interface, with a specific start level
 * @param f/*from w  ww  .j ava2 s.com*/
 * @param startBundle
 * @param startLevel
 * @return the sling response
 * @throws ClientException
 */
public SlingHttpResponse installBundle(File f, boolean startBundle, int startLevel) throws ClientException {
    // Setup request for Felix Webconsole bundle install
    MultipartEntityBuilder builder = MultipartEntityBuilder.create().addTextBody("action", "install")
            .addBinaryBody("bundlefile", f);
    if (startBundle) {
        builder.addTextBody("bundlestart", "true");
    }
    if (startLevel > 0) {
        builder.addTextBody("bundlestartlevel", String.valueOf(startLevel));
        LOG.info("Installing bundle {} at start level {}", f.getName(), startLevel);
    } else {
        LOG.info("Installing bundle {} at default start level", f.getName());
    }

    return this.doPost(URL_BUNDLES, builder.build(), 302);

}

From source file:com.tur0kk.facebook.FacebookClient.java

public String publishPicture(String msg, Image image, String placeId) throws IOException {
    OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/v2.2/me/photos"); // request node
    request.addHeader("Authorization", "Bearer " + accesTokenString); // authentificate

    // check input to avoid error responses
    if (msg != null && image != null) {
        // facebook requires multipart post structure
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("message", msg); // description

        if (placeId != null && !"".equals(placeId)) {
            builder.addTextBody("place", placeId); // add link to FabLab site if property is set in preferences
        }/*from w  w w  . j a  v  a  2 s . c  o m*/

        // convert image to bytearray and append to multipart
        BufferedImage bimage = new BufferedImage(image.getWidth(null), image.getHeight(null),
                BufferedImage.TYPE_INT_ARGB);
        Graphics2D bGr = bimage.createGraphics();
        bGr.drawImage(image, 0, 0, null);
        bGr.dispose();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bimage, "png", baos);
        builder.addBinaryBody(msg, baos.toByteArray(), ContentType.MULTIPART_FORM_DATA, "test.png");

        // generate multipart byte stream and add to payload of post package
        HttpEntity multipart = builder.build();
        ByteArrayOutputStream multipartOutStream = new ByteArrayOutputStream(
                (int) multipart.getContentLength());
        multipart.writeTo(multipartOutStream);
        request.addPayload(multipartOutStream.toByteArray());

        // set header of post package
        Header contentType = multipart.getContentType();
        request.addHeader(contentType.getName(), contentType.getValue());

        // send and response answer
        Response response = request.send();
        return response.getBody();
    } else {
        throw new RuntimeException("message and image needed");
    }
}

From source file:com.tremolosecurity.proxy.postProcess.PushRequestProcess.java

@Override
public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpFilterChain chain)
        throws Exception {
    boolean isText;

    HashMap<String, String> uriParams = (HashMap<String, String>) req.getAttribute("TREMOLO_URI_PARAMS");

    StringBuffer proxyToURL = new StringBuffer();

    proxyToURL.append(holder.getProxyURL(uriParams));

    boolean first = true;
    for (NVP p : req.getQueryStringParams()) {
        if (first) {
            proxyToURL.append('?');
            first = false;//from w  w w  .  j av a 2 s .  c  om
        } else {
            proxyToURL.append('&');
        }

        proxyToURL.append(p.getName()).append('=').append(URLEncoder.encode(p.getValue(), "UTF-8"));
    }

    HttpEntity entity = null;

    if (req.isMultiPart()) {

        MultipartEntityBuilder mpeb = MultipartEntityBuilder.create()
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (String name : req.getFormParams()) {

            /*if (queryParams.contains(name)) {
               continue;
            }*/

            for (String val : req.getFormParamVals(name)) {
                //ent.addPart(name, new StringBody(val));
                mpeb.addTextBody(name, val);
            }

        }

        HashMap<String, ArrayList<FileItem>> files = req.getFiles();
        for (String name : files.keySet()) {
            for (FileItem fi : files.get(name)) {
                //ent.addPart(name, new InputStreamBody(fi.getInputStream(),fi.getContentType(),fi.getName()));

                mpeb.addBinaryBody(name, fi.get(), ContentType.create(fi.getContentType()), fi.getName());

            }
        }

        entity = mpeb.build();

    } else if (req.isParamsInBody()) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        for (String paramName : req.getFormParams()) {

            for (String val : req.getFormParamVals(paramName)) {

                formparams.add(new BasicNameValuePair(paramName, val));
            }
        }

        entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    } else {

        byte[] msgData = (byte[]) req.getAttribute(ProxySys.MSG_BODY);
        ByteArrayEntity bentity = new ByteArrayEntity(msgData);
        bentity.setContentType(req.getContentType());

        entity = bentity;
    }

    MultipartRequestEntity frm;

    CloseableHttpClient httpclient = this.getHttp(proxyToURL.toString(), req.getServletRequest(),
            holder.getConfig());

    //HttpPost httppost = new HttpPost(proxyToURL.toString());
    HttpEntityEnclosingRequestBase httpMethod = new EntityMethod(req.getMethod(), proxyToURL.toString());//this.getHttpMethod(proxyToURL.toString());

    setHeadersCookies(req, holder, httpMethod, proxyToURL.toString());

    httpMethod.setEntity(entity);

    HttpContext ctx = (HttpContext) req.getSession().getAttribute(ProxySys.HTTP_CTX);
    HttpResponse response = httpclient.execute(httpMethod, ctx);

    postProcess(req, resp, holder, response, proxyToURL.toString(), chain, httpMethod);

}

From source file:aajavafx.VisitorController.java

@FXML
private void handleSave(ActionEvent event) {
    if (imageFile != null) {

        String visitorId = visitorIDField.getText();
        visitorIDField.clear();/*w w w.  ja  v  a  2s  . c  o m*/
        String firstName = firstNameField.getText();
        firstNameField.clear();
        String lastName = lastNameField.getText();
        lastNameField.clear();
        String email = emailField.getText();
        emailField.clear();
        String phoneNumber = phoneNumberField.getText();
        phoneNumberField.clear();
        Integer companyId = getCompanyIDFromName(companyBox.getValue().toString());
        try {
            Gson gson = new Gson();
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc
            if (visitorIDField.isEditable()) { //then we are posting a new record
                HttpEntity = new HttpPost(VisitorsRootURL); //so make a http post object
            } else { //we are editing a record 
                HttpEntity = new HttpPut(VisitorsRootURL); //so make a http put object
            }
            Company company = getCompany(companyId);
            Visitors visitor = new Visitors(visitorId, firstName, lastName, email, phoneNumber, company);

            String jsonString = new String(gson.toJson(visitor));
            System.out.println("json string: " + jsonString);
            StringEntity postString = new StringEntity(jsonString);

            HttpEntity.setEntity(postString);
            HttpEntity.setHeader("Content-type", "application/json");
            HttpResponse response = httpClient.execute(HttpEntity);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 204) {
                System.out.println("New visitor posted successfully");
            } else {
                System.out.println("Server error: " + response.getStatusLine());
            }
            visitorIDField.setEditable(false);
            firstNameField.setEditable(false);
            lastNameField.setEditable(false);
            emailField.setEditable(false);
            phoneNumberField.setEditable(false);
            companyBox.setEditable(false);
            visitorIDField.clear();
            firstNameField.clear();
            lastNameField.clear();
            emailField.clear();
            tableVisitors.setItems(getVisitors());
        } catch (UnsupportedEncodingException ex) {
            System.out.println(ex);
        } catch (IOException e) {
            System.out.println(e);
        } catch (JSONException je) {
            System.out.println("JSON error: " + je);
        }

        FileInputStream fis = null;
        try {

            fis = new FileInputStream(imageFile);
            HttpClient httpClient = HttpClientBuilder.create().build();
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            FileBody fileBody = new FileBody(new File(imageFile.getName())); //image should be a String
            builder.addPart("file", new InputStreamBody(fis, imageFile.getName()));
            //builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // server back-end URL
            HttpPost httppost = new HttpPost(postHTML);
            //MultipartEntity entity = new MultipartEntity();
            // set the file input stream and file name as arguments
            //entity.addPart("file", new InputStreamBody(fis, inFile.getName()));
            HttpEntity entity = builder.build();
            httppost.setEntity(entity);
            // execute the request
            HttpResponse response = httpClient.execute(httppost);

            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity responseEntity = response.getEntity();
            String responseString = EntityUtils.toString(responseEntity, "UTF-8");

            System.out.println("[" + statusCode + "] " + responseString);

        } catch (ClientProtocolException e) {
            System.err.println("Unable to make connection");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Unable to read file");
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
            }
        }

    } else {
        errorLabel.setText("Record Not Saved: Please attach a photo for this visitor");
        errorLabel.setVisible(true);
    }

}

From source file:com.frochr123.fabqr.FabQRFunctions.java

public static void uploadFabQRProject(String name, String email, String projectName, int licenseIndex,
        String tools, String description, String location, BufferedImage imageReal, BufferedImage imageScheme,
        PlfFile plfFile, String lasercutterName, String lasercutterMaterial) throws Exception {
    // Check for valid situation, otherwise abort
    if (MainView.getInstance() == null || VisicutModel.getInstance() == null
            || VisicutModel.getInstance().getPlfFile() == null || !isFabqrActive()
            || getFabqrPrivateURL() == null || getFabqrPrivateURL().isEmpty()
            || MaterialManager.getInstance() == null || MappingManager.getInstance() == null
            || VisicutModel.getInstance().getSelectedLaserDevice() == null) {
        throw new Exception("FabQR upload exception: Critical error");
    }//w  w w.  java2 s. c o m

    // Check valid data
    if (name == null || email == null || projectName == null || projectName.length() < 3 || licenseIndex < 0
            || tools == null || tools.isEmpty() || description == null || description.isEmpty()
            || location == null || location.isEmpty() || imageScheme == null || plfFile == null
            || lasercutterName == null || lasercutterName.isEmpty() || lasercutterMaterial == null
            || lasercutterMaterial.isEmpty()) {
        throw new Exception("FabQR upload exception: Invalid input data");
    }

    // Convert images to byte data for PNG, imageReal is allowed to be empty
    byte[] imageSchemeBytes = null;
    ByteArrayOutputStream imageSchemeOutputStream = new ByteArrayOutputStream();
    PreviewImageExport.writePngToOutputStream(imageSchemeOutputStream, imageScheme);
    imageSchemeBytes = imageSchemeOutputStream.toByteArray();

    if (imageSchemeBytes == null) {
        throw new Exception("FabQR upload exception: Error converting scheme image");
    }

    byte[] imageRealBytes = null;

    if (imageReal != null) {
        // Need to convert image, ImageIO.write messes up the color space of the original input image
        BufferedImage convertedImage = new BufferedImage(imageReal.getWidth(), imageReal.getHeight(),
                BufferedImage.TYPE_3BYTE_BGR);
        ColorConvertOp op = new ColorConvertOp(null);
        op.filter(imageReal, convertedImage);

        ByteArrayOutputStream imageRealOutputStream = new ByteArrayOutputStream();
        ImageIO.write(convertedImage, "jpg", imageRealOutputStream);
        imageRealBytes = imageRealOutputStream.toByteArray();
    }

    // Extract all URLs from used QR codes
    List<String> referencesList = new LinkedList<String>();
    List<PlfPart> plfParts = plfFile.getPartsCopy();

    for (PlfPart plfPart : plfParts) {
        if (plfPart.getQRCodeInfo() != null && plfPart.getQRCodeInfo().getQRCodeSourceURL() != null
                && !plfPart.getQRCodeInfo().getQRCodeSourceURL().trim().isEmpty()) {
            // Process url, if it is URL of a FabQR system, remove download flag and point to project page instead
            // Use regex to check for FabQR system URL structure
            String qrCodeUrl = plfPart.getQRCodeInfo().getQRCodeSourceURL().trim();

            // Check for temporary URL structure of FabQR system
            Pattern fabQRUrlTemporaryPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_TEMPORARY_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            // Do not include link if it is just temporary
            if (fabQRUrlTemporaryPattern.matcher(qrCodeUrl).find()) {
                continue;
            }

            // Check for download URL structure of FabQR system
            // Change URL to point to project page instead
            Pattern fabQRUrlDownloadPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_DOWNLOAD_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            if (fabQRUrlDownloadPattern.matcher(qrCodeUrl).find()) {
                qrCodeUrl = qrCodeUrl.replace("/" + FABQR_DOWNLOAD_MARKER + "/", "/");
            }

            // Add URL if it is not yet in list
            if (!referencesList.contains(qrCodeUrl)) {
                referencesList.add(qrCodeUrl);
            }
        }
    }

    String references = "";

    for (String ref : referencesList) {
        // Add comma for non first entries
        if (!references.isEmpty()) {
            references = references + ",";
        }

        references = references + ref;
    }

    // Get bytes for PLF file
    byte[] plfFileBytes = null;
    ByteArrayOutputStream plfFileOutputStream = new ByteArrayOutputStream();
    VisicutModel.getInstance().savePlfToStream(MaterialManager.getInstance(), MappingManager.getInstance(),
            plfFileOutputStream);
    plfFileBytes = plfFileOutputStream.toByteArray();

    if (plfFileBytes == null) {
        throw new Exception("FabQR upload exception: Error saving PLF file");
    }

    // Begin uploading data
    String uploadUrl = getFabqrPrivateURL() + FABQR_API_UPLOAD_PROJECT;

    // Create HTTP client and cusomized config for timeouts
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(FABQR_UPLOAD_TIMEOUT)
            .setConnectTimeout(FABQR_UPLOAD_TIMEOUT).setConnectionRequestTimeout(FABQR_UPLOAD_TIMEOUT).build();

    // Create HTTP Post request and entity builder
    HttpPost httpPost = new HttpPost(uploadUrl);
    httpPost.setConfig(requestConfig);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    // Insert file uploads
    multipartEntityBuilder.addBinaryBody("imageScheme", imageSchemeBytes, ContentType.APPLICATION_OCTET_STREAM,
            "imageScheme.png");
    multipartEntityBuilder.addBinaryBody("inputFile", plfFileBytes, ContentType.APPLICATION_OCTET_STREAM,
            "inputFile.plf");

    // Image real is allowed to be null, if it is not, send it
    if (imageRealBytes != null) {
        multipartEntityBuilder.addBinaryBody("imageReal", imageRealBytes, ContentType.APPLICATION_OCTET_STREAM,
                "imageReal.png");
    }

    // Prepare content type for text data, especially needed for correct UTF8 encoding
    ContentType contentType = ContentType.create("text/plain", Consts.UTF_8);

    // Insert text data
    multipartEntityBuilder.addTextBody("name", name, contentType);
    multipartEntityBuilder.addTextBody("email", email, contentType);
    multipartEntityBuilder.addTextBody("projectName", projectName, contentType);
    multipartEntityBuilder.addTextBody("licenseIndex", new Integer(licenseIndex).toString(), contentType);
    multipartEntityBuilder.addTextBody("tools", tools, contentType);
    multipartEntityBuilder.addTextBody("description", description, contentType);
    multipartEntityBuilder.addTextBody("location", location, contentType);
    multipartEntityBuilder.addTextBody("lasercutterName", lasercutterName, contentType);
    multipartEntityBuilder.addTextBody("lasercutterMaterial", lasercutterMaterial, contentType);
    multipartEntityBuilder.addTextBody("references", references, contentType);

    // Assign entity to this post request
    HttpEntity httpEntity = multipartEntityBuilder.build();
    httpPost.setEntity(httpEntity);

    // Set authentication information
    String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(),
            FabQRFunctions.getFabqrPrivatePassword());
    if (!encodedCredentials.isEmpty()) {
        httpPost.addHeader("Authorization", "Basic " + encodedCredentials);
    }

    // Send request
    CloseableHttpResponse res = httpClient.execute(httpPost);

    // React to possible server side errors
    if (res.getStatusLine() == null || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new Exception("FabQR upload exception: Server sent wrong HTTP status code: "
                + new Integer(res.getStatusLine().getStatusCode()).toString());
    }

    // Close everything correctly
    res.close();
    httpClient.close();
}

From source file:com.adobe.aem.demo.communities.Loader.java

private static String doThumbnail(String hostname, String port, String adminPassword, String csvfile,
        String filename) {//from   ww w  .  ja  v  a 2  s  .c o  m

    String pathToFile = "/content/dam/communities/resource-thumbnails/" + filename;
    File attachment = new File(csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator + filename);

    ContentType ct = ContentType.MULTIPART_FORM_DATA;
    if (filename.indexOf(".mp4") > 0) {
        ct = ContentType.create("video/mp4", MIME.UTF8_CHARSET);
    } else if (filename.indexOf(".jpg") > 0 || filename.indexOf(".jpeg") > 0) {
        ct = ContentType.create("image/jpeg", MIME.UTF8_CHARSET);
    } else if (filename.indexOf(".png") > 0) {
        ct = ContentType.create("image/png", MIME.UTF8_CHARSET);
    }

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(MIME.UTF8_CHARSET);
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addBinaryBody("file", attachment, ct, attachment.getName());
    builder.addTextBody("fileName", filename, ContentType.create("text/plain", MIME.UTF8_CHARSET));

    logger.debug(
            "Adding file for thumbnails with name: " + attachment.getName() + " and type: " + ct.getMimeType());

    Loader.doPost(hostname, port, pathToFile, "admin", adminPassword, builder.build(), null);

    logger.debug("Path to thumbnail: " + pathToFile);

    return pathToFile + "/file";

}

From source file:net.ychron.unirestinst.request.body.MultipartBody.java

public HttpEntity getEntity() {
    if (hasFile) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (mode != null) {
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        }/*w w w. j  a v  a2s  .  c  o m*/
        for (String key : parameters.keySet()) {
            List<Object> value = parameters.get(key);
            ContentType contentType = contentTypes.get(key);
            for (Object cur : value) {
                if (cur instanceof File) {
                    File file = (File) cur;
                    builder.addPart(key, new FileBody(file, contentType, file.getName()));
                } else if (cur instanceof InputStreamBody) {
                    builder.addPart(key, (ContentBody) cur);
                } else if (cur instanceof ByteArrayBody) {
                    builder.addPart(key, (ContentBody) cur);
                } else {
                    builder.addPart(key, new StringBody(cur.toString(), contentType));
                }
            }
        }
        return builder.build();
    } else {
        try {
            return new UrlEncodedFormEntity(MapUtil.getList(parameters), UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.portfolio.data.attachment.XSLService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**//from w  ww  . j  ava  2 s. com
     * Format demand:
     * <convert>
     *   <portfolioid>{uuid}</portfolioid>
     *   <portfolioid>{uuid}</portfolioid>
     *   <nodeid>{uuid}</nodeid>
     *   <nodeid>{uuid}</nodeid>
     *   <documentid>{uuid}</documentid>
     *   <xsl>{rpertoire}{fichier}</xsl>
     *   <format>[pdf rtf xml ...]</format>
     *   <parameters>
     *     <maVar1>lala</maVar1>
     *     ...
     *   </parameters>
     * </convert>
     */
    try {
        //On initialise le dataProvider
        Connection c = null;
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String origin = request.getRequestURL().toString();

    /// Variable stuff
    int userId = 0;
    int groupId = 0;
    String user = "";
    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    /// TODO: A voire si un form get ne ferait pas l'affaire aussi

    /// On lis le xml
    /*
    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while( (line = rd.readLine()) != null )
       sb.append(line);
            
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    Document doc=null;
    try
    {
       documentBuilder = documentBuilderFactory.newDocumentBuilder();
       doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
            
    /// On lit les paramtres
    NodeList portfolioNode = doc.getElementsByTagName("portfolioid");
    NodeList nodeNode = doc.getElementsByTagName("nodeid");
    NodeList documentNode = doc.getElementsByTagName("documentid");
    NodeList xslNode = doc.getElementsByTagName("xsl");
    NodeList formatNode = doc.getElementsByTagName("format");
    NodeList parametersNode = doc.getElementsByTagName("parameters");
    //*/
    //      String xslfile = xslNode.item(0).getTextContent();
    String xslfile = request.getParameter("xsl");
    String format = request.getParameter("format");
    //      String format = formatNode.item(0).getTextContent();
    String parameters = request.getParameter("parameters");
    String documentid = request.getParameter("documentid");
    String portfolios = request.getParameter("portfolioids");
    String[] portfolioid = null;
    if (portfolios != null)
        portfolioid = portfolios.split(";");
    String nodes = request.getParameter("nodeids");
    String[] nodeid = null;
    if (nodes != null)
        nodeid = nodes.split(";");

    System.out.println("PARAMETERS: ");
    System.out.println("xsl: " + xslfile);
    System.out.println("format: " + format);
    System.out.println("user: " + userId);
    System.out.println("portfolioids: " + portfolios);
    System.out.println("nodeids: " + nodes);
    System.out.println("parameters: " + parameters);

    boolean redirectDoc = false;
    if (documentid != null) {
        redirectDoc = true;
        System.out.println("documentid @ " + documentid);
    }

    boolean usefop = false;
    String ext = "";
    if (MimeConstants.MIME_PDF.equals(format)) {
        usefop = true;
        ext = ".pdf";
    } else if (MimeConstants.MIME_RTF.equals(format)) {
        usefop = true;
        ext = ".rtf";
    }
    //// Paramtre portfolio-uuid et file-xsl
    //      String uuid = request.getParameter("uuid");
    //      String xslfile = request.getParameter("xsl");

    StringBuilder aggregate = new StringBuilder();
    try {
        int portcount = 0;
        int nodecount = 0;
        // On aggrge les donnes
        if (portfolioid != null) {
            portcount = portfolioid.length;
            for (int i = 0; i < portfolioid.length; ++i) {
                String p = portfolioid[i];
                String portfolioxml = dataProvider
                        .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0)
                        .toString();
                aggregate.append(portfolioxml);
            }
        }

        if (nodeid != null) {
            nodecount = nodeid.length;
            for (int i = 0; i < nodeid.length; ++i) {
                String n = nodeid[i];
                String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "")
                        .toString();
                aggregate.append(nodexml);
            }
        }

        // Est-ce qu'on a eu besoin d'aggrger les donnes?
        String input = aggregate.toString();
        String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration

        input = input.replaceAll(pattern, "");

        input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet ["
                + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir
                + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \""
                + servletDir + "xhtml-symbol.ent\">"
                + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir
                + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters
                "<root>" + input + "</root>";

        //         System.out.println("INPUT WITH PROXY:"+ input);

        /// Rsolution des proxys
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(input));
        Document doc = documentBuilder.parse(is);

        /// Proxy stuff
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//asmResource[@xsi_type='Proxy']";
        String filterCode = "./code/text()";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        XPathExpression codeFilter = xPath.compile(filterCode);

        for (int i = 0; i < nodelist.getLength(); ++i) {
            Node res = nodelist.item(i);
            Node gp = res.getParentNode(); // resource -> context -> container
            Node ggp = gp.getParentNode();
            Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE);

            /// Fetch node we want to replace
            String returnValue = dataProvider
                    .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "")
                    .toString();

            Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue)));
            Element repNode = rep.getDocumentElement();
            Node proxyNode = repNode.getFirstChild();
            proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned
            //            doc.replaceChild(proxyNode, gp);
            ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work.
            ggp.removeChild(gp);
        }

        try // Convert XML document to string
        {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            writer.flush();
            input = writer.toString();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }

        //         System.out.println("INPUT DATA:"+ input);

        // Setup a buffer to obtain the content length
        ByteArrayOutputStream stageout = new ByteArrayOutputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //// Setup Transformer (1st stage)
        /// Base path
        String basepath = xslfile.substring(0, xslfile.indexOf(File.separator));
        String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator
                + "xsl" + File.separator + "html2xml.xsl";
        System.out.println("FIRST: " + firstStage);
        Source xsltSrc1 = new StreamSource(new File(firstStage));
        Transformer transformer1 = transFactory.newTransformer(xsltSrc1);
        StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes()));
        Result stageRes = new StreamResult(stageout);
        transformer1.transform(stageSource, stageRes);

        // Setup Transformer (2nd stage)
        String secondStage = baseDir + File.separator + xslfile;
        Source xsltSrc2 = new StreamSource(new File(secondStage));
        Transformer transformer2 = transFactory.newTransformer(xsltSrc2);

        // Configure parameter from xml
        String[] table = parameters.split(";");
        for (int i = 0; i < table.length; ++i) {
            String line = table[i];
            int var = line.indexOf(":");
            String par = line.substring(0, var);
            String val = line.substring(var + 1);
            transformer2.setParameter(par, val);
        }

        // Setup input
        StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes()));
        //         StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") );

        Result res = null;
        if (usefop) {
            /// FIXME: Might need to include the entity for html stuff?
            //Setup FOP
            //Make sure the XSL transformation's result is piped through to FOP
            Fop fop = fopFactory.newFop(format, out);

            res = new SAXResult(fop.getDefaultHandler());

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        } else {
            res = new StreamResult(out);

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        }

        if (redirectDoc) {

            // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]
            String urlTarget = "http://" + server + "/resources/resource/file/" + documentid;
            System.out.println("Redirect @ " + urlTarget);

            HttpClientBuilder clientbuilder = HttpClientBuilder.create();
            CloseableHttpClient client = clientbuilder.build();

            HttpPost post = new HttpPost(urlTarget);
            post.addHeader("referer", origin);
            String sessionid = request.getSession().getId();
            System.out.println("Session: " + sessionid);
            post.addHeader("Cookie", "JSESSIONID=" + sessionid);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext);

            builder.addPart("uploadfile", body);

            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse ret = client.execute(post);
            String stringret = new BasicResponseHandler().handleResponse(ret);

            int code = ret.getStatusLine().getStatusCode();
            response.setStatus(code);
            ServletOutputStream output = response.getOutputStream();
            output.write(stringret.getBytes(), 0, stringret.length());
            output.close();
            client.close();

            /*
            HttpURLConnection connection = CreateConnection( urlTarget, request );
                    
            /// Helping construct Json
            connection.setRequestProperty("referer", origin);
                    
            /// Send post data
            ServletInputStream inputData = request.getInputStream();
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
                    
            byte[] buffer = new byte[1024];
            int dataSize;
            while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
            {
               writer.write(buffer, 0, dataSize);
            }
            inputData.close();
            writer.close();
                    
            RetrieveAnswer(connection, response, origin);
            //*/
        } else {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=generated" + ext);
            response.setContentType(format);
            response.setContentLength(out.size());
            response.getOutputStream().write(out.toByteArray());
            response.getOutputStream().flush();
        }
    } catch (Exception e) {
        String message = e.getMessage();
        response.setStatus(500);
        response.getOutputStream().write(message.getBytes());
        response.getOutputStream().close();

        e.printStackTrace();
    } finally {
        dataProvider.disconnect();
    }
}