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.qmetry.qaf.automation.integration.qmetry.qmetry6.patch.QMetryRestWebservice.java

/**
 * attach log using run id/*  w  w w  .  j  ava2  s.c o m*/
 * 
 * @param token
 *            - token generate using username and password
 * @param projectID
 * @param releaseID
 * @param cycleID
 * @param testCaseRunId
 * @param filePath
 *            - absolute path of file to be attached
 * @return
 */
public int attachTestLogsUsingRunId(String token, String projectID, String releaseID, String cycleID,
        long testCaseRunId, File filePath) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(baseURL + "/rest/attachments/testLog");

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

                FileBody bin = new FileBody(filePath);
                builder.addTextBody("desc", "Attached on " + CurrentDate, ContentType.TEXT_PLAIN);
                builder.addTextBody("type", "TCR", ContentType.TEXT_PLAIN);
                builder.addTextBody("entityId", String.valueOf(testCaseRunId), ContentType.TEXT_PLAIN);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", projectID + ":" + releaseID + ":" + cycleID);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:connection.ChaperOnConnection.java

private HttpPost GetPostHTTP(String email, String password, String firstname, String username, String imagePath,
        String street, String apartment, String city, String postal, String country, String lastname,
        String description, int rideType, double lattitude, double longitude, String phone, int availableseats,
        String licenseImage) {//from   w  w  w.java  2 s  . c  o m
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
    Bitmap bitmap2 = BitmapFactory.decodeFile(licenseImage);
    HttpPost request = new HttpPost(REGISTER_URL);
    String param = "{\"phone\":\"" + phone + "\",\"email\":\"" + email + "\",\"password\": \"" + password
            + "\",\"username\": \"" + username + "\",\"availableSeats\":" + availableseats + ",\"type\": "
            + rideType + ",\"lattitude\": " + lattitude + ",\"longtitude\": " + longitude + ",\"street\": \""
            + street + "\",\"appartment\": \"" + apartment + "\",\"city\": \"" + city + "\",\"zip\": \""
            + postal + "\",\"country\": \"" + country + "\",\"lname\": \"" + lastname + "\",\"description\": \""
            + description + "\",\"fname\": \"" + firstname + "\"}";
    String BOUNDARY = "---------------------------41184676334";
    request.setHeader("enctype", "multipart/form-data; boundary=" + BOUNDARY);
    request.setHeader("app-id", "appid");
    request.setHeader("app-key", "appkey");

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();

    try {
        entity.addPart("data", new StringBody(param));

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, bos);
        bitmap2.compress(Bitmap.CompressFormat.JPEG, 70, bos2);

        InputStream in = new ByteArrayInputStream(bos.toByteArray());
        InputStream in2 = new ByteArrayInputStream(bos2.toByteArray());

        ContentBody image = new InputStreamBody(in, "image/jpeg");
        ContentBody image2 = new InputStreamBody(in2, "image/jpeg");
        entity.addPart("image", image);
        entity.addPart("licenceimage", image2);

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    request.setEntity(entity.build());
    return request;
}

From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java

@Override
public final <RS> Will<Response<RS>> post(String resource, MultiPartRequest request, Class<RS> clazz)
        throws RestEndpointIOException {
    HttpPost post = new HttpPost(spliceUrl(resource));

    try {//from  w  ww  .  j a  va2 s. c  om

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        for (MultiPartRequest.MultiPartSerialized<?> serializedPart : request.getSerializedRQs()) {
            Serializer serializer = getSupportedSerializer(serializedPart);
            builder.addPart(serializedPart.getPartName(),
                    new StringBody(new String(serializer.serialize(serializedPart.getRequest())),
                            ContentType.parse(serializer.getMimeType())));
        }

        for (MultiPartRequest.MultiPartBinary partBinaty : request.getBinaryRQs()) {
            builder.addPart(partBinaty.getPartName(), new ByteArrayBody(partBinaty.getData().read(),
                    ContentType.parse(partBinaty.getContentType()), partBinaty.getFilename()));
        }

        /* Here is some dirty hack to avoid problem with MultipartEntity and asynchronous http client
         *  Details can be found here: http://comments.gmane.org/gmane.comp.apache.httpclient.user/2426
         *
         *  The main idea is to replace MultipartEntity with NByteArrayEntity once first
         * doesn't support #getContent method
         *  which is required for async client implementation. So, we are copying response
         *  body as byte array to NByteArrayEntity to
         *  leave it unmodified.
         *
         *  Alse we need to add boundary value to content type header. Details are here:
         *  http://en.wikipedia.org/wiki/Delimiter#Content_boundary
         *  MultipartEntity generates correct header by yourself, but we need to put it
         *  manually once we replaced entity type to NByteArrayEntity
         */
        String boundary = "-------------" + UUID.randomUUID().toString();
        builder.setBoundary(boundary);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        builder.build().writeTo(baos);

        post.setEntity(new NByteArrayEntity(baos.toByteArray(), ContentType.MULTIPART_FORM_DATA));
        post.setHeader("Content-Type", "multipart/form-data;boundary=" + boundary);

    } catch (Exception e) {
        throw new RestEndpointIOException("Unable to build post multipart request", e);
    }
    return executeInternal(post, new ClassConverterCallback<RS>(serializers, clazz));
}

From source file:org.apache.stanbol.workflow.jersey.writers.ContentItemWriter.java

@Override
public void writeTo(ContentItem ci, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {

    //(0) handle default dataType
    Map<String, Object> reqProp = ContentItemHelper.getRequestPropertiesContentPart(ci);
    boolean omitMetadata = isOmitMetadata(reqProp);
    if (!MULTIPART.isCompatible(mediaType)) { //two possible cases
        if (!omitMetadata) { //  (1) just return the RDF data
            //(1.a) Backward support for default dataType if no Accept header is set
            StringBuilder ctb = new StringBuilder();
            if (mediaType.isWildcardType() || TEXT_PLAIN_TYPE.isCompatible(mediaType)
                    || APPLICATION_OCTET_STREAM_TYPE.isCompatible(mediaType)) {
                ctb.append(APPLICATION_LD_JSON);
            } else {
                ctb.append(mediaType.getType()).append('/').append(mediaType.getSubtype());
            }/*from  w  w w .j ava 2 s  .c  o m*/
            ctb.append(";charset=").append(UTF8.name());
            String contentType = ctb.toString();
            httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType);
            try {
                serializer.serialize(entityStream, ci.getMetadata(), contentType);
            } catch (UnsupportedSerializationFormatException e) {
                throw new WebApplicationException("The enhancement results "
                        + "cannot be serialized in the requested media type: " + mediaType.toString(),
                        Response.Status.NOT_ACCEPTABLE);
            }
        } else { //  (2) return a single content part
            Entry<UriRef, Blob> contentPart = getBlob(ci, Collections.singleton(mediaType.toString()));
            if (contentPart == null) { //no alternate content with the requeste media type
                throw new WebApplicationException("The requested enhancement chain has not created an "
                        + "version of the parsed content in the reuqest media type " + mediaType.toString(),
                        Response.Status.UNSUPPORTED_MEDIA_TYPE);
            } else { //found -> stream the content to the client
                //NOTE: This assumes that the presence of a charset
                //      implies reading/writing character streams
                String requestedCharset = mediaType.getParameters().get("charset");
                String blobCharset = contentPart.getValue().getParameter().get("charset");
                Charset readerCharset = blobCharset == null ? UTF8 : Charset.forName(blobCharset);
                Charset writerCharset = requestedCharset == null ? null : Charset.forName(requestedCharset);
                if (writerCharset != null && !writerCharset.equals(readerCharset)) {
                    //we need to transcode
                    Reader reader = new InputStreamReader(contentPart.getValue().getStream(), readerCharset);
                    Writer writer = new OutputStreamWriter(entityStream, writerCharset);
                    IOUtils.copy(reader, writer);
                    IOUtils.closeQuietly(reader);
                } else { //no transcoding
                    if (requestedCharset == null && blobCharset != null) {
                        httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE,
                                mediaType.toString() + "; charset=" + blobCharset);
                    }
                    InputStream in = contentPart.getValue().getStream();
                    IOUtils.copy(in, entityStream);
                    IOUtils.closeQuietly(in);
                }
            }
        }
    } else { // multipart mime requested!
        final String charsetName = mediaType.getParameters().get("charset");
        final Charset charset = charsetName != null ? Charset.forName(charsetName) : UTF8;
        MediaType rdfFormat;
        String rdfFormatString = getRdfFormat(reqProp);
        if (rdfFormatString == null || rdfFormatString.isEmpty()) {
            rdfFormat = DEFAULT_RDF_FORMAT;
        } else {
            try {
                rdfFormat = MediaType.valueOf(rdfFormatString);
                if (rdfFormat.getParameters().get("charset") == null) {
                    //use the charset of the default RDF format
                    rdfFormat = new MediaType(rdfFormat.getType(), rdfFormat.getSubtype(),
                            DEFAULT_RDF_FORMAT.getParameters());
                }
            } catch (IllegalArgumentException e) {
                throw new WebApplicationException(
                        "The specified RDF format '" + rdfFormatString
                                + "' (used to serialize all RDF parts of "
                                + "multipart MIME responses) is not a well formated MIME type",
                        Response.Status.BAD_REQUEST);
            }
        }
        //(1) setting the correct header
        String contentType = String.format("%s/%s; charset=%s; boundary=%s", mediaType.getType(),
                mediaType.getSubtype(), charset.toString(), CONTENT_ITEM_BOUNDARY);
        httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setBoundary(CONTENT_ITEM_BOUNDARY);
        //HttpMultipart entity = new HttpMultipart("from-data", charset ,CONTENT_ITEM_BOUNDARY);
        //(2) serialising the metadata
        if (!isOmitMetadata(reqProp)) {
            entityBuilder.addPart("metadata",
                    new ClerezzaContentBody(ci.getUri().getUnicodeString(), ci.getMetadata(), rdfFormat));
            //                entity.addBodyPart(new FormBodyPart("metadata", new ClerezzaContentBody(
            //                    ci.getUri().getUnicodeString(), ci.getMetadata(),
            //                    rdfFormat)));
        }
        //(3) serialising the Content (Bloby)
        //(3.a) Filter based on parameter
        List<Entry<UriRef, Blob>> includedBlobs = filterBlobs(ci, reqProp);
        //(3.b) Serialise the filtered
        if (!includedBlobs.isEmpty()) {
            Map<String, ContentBody> contentParts = new LinkedHashMap<String, ContentBody>();
            for (Entry<UriRef, Blob> entry : includedBlobs) {
                Blob blob = entry.getValue();
                ContentType ct = ContentType.create(blob.getMimeType());
                String cs = blob.getParameter().get("charset");
                if (StringUtils.isNotBlank(cs)) {
                    ct = ct.withCharset(cs);
                }
                contentParts.put(entry.getKey().getUnicodeString(), new InputStreamBody(blob.getStream(), ct));
            }
            //add all the blobs
            entityBuilder.addPart("content",
                    new MultipartContentBody(contentParts, CONTENT_PARTS_BOUNDERY, MULTIPART_ALTERNATE));
        } //else no content to include
        Set<String> includeContentParts = getIncludedContentPartURIs(reqProp);
        if (includeContentParts != null) {
            //(4) serialise the Request Properties
            if (includeContentParts.isEmpty()
                    || includeContentParts.contains(REQUEST_PROPERTIES_URI.getUnicodeString())) {
                JSONObject object;
                try {
                    object = toJson(reqProp);
                } catch (JSONException e) {
                    String message = "Unable to convert Request Properties " + "to JSON (values : " + reqProp
                            + ")!";
                    log.error(message, e);
                    throw new WebApplicationException(message, Response.Status.INTERNAL_SERVER_ERROR);
                }
                entityBuilder.addTextBody(REQUEST_PROPERTIES_URI.getUnicodeString(), object.toString(),
                        ContentType.APPLICATION_JSON.withCharset(UTF8));
            }
            //(5) additional RDF metadata stored in contentParts
            for (Entry<UriRef, TripleCollection> entry : getContentParts(ci, TripleCollection.class)
                    .entrySet()) {
                if (includeContentParts.isEmpty() || includeContentParts.contains(entry.getKey())) {
                    entityBuilder.addPart(entry.getKey().getUnicodeString(), new ClerezzaContentBody(null, //no file name
                            entry.getValue(), rdfFormat));
                } // else ignore this content part
            }
        }
        entityBuilder.build().writeTo(entityStream);
    }

}

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**/* ww  w. ja  v a 2 s . c  o  m*/
     * 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();
    }
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry7.QMetryRestWebservice.java

public int attachTestLogs(long tcVersionIdASEntityId, File filePath) {
    try {/*from   w ww.j  a  v a2 s  . c  o  m*/
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments");

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

                FileBody bin = new FileBody(filePath);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", scope);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:org.openestate.is24.restapi.hc43.HttpComponents43Client.java

@Override
protected Response sendVideoUploadRequest(URL url, RequestMethod method, String auth, InputStream input,
        String fileName, final long fileSize) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;//  ww  w . ja va2s.co m
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");

    HttpUriRequest request = null;
    if (RequestMethod.POST.equals(method)) {
        request = new HttpPost(url.toString());
    } else if (RequestMethod.PUT.equals(method)) {
        request = new HttpPut(url.toString());
    } else {
        throw new IOException("Unsupported request method '" + method + "'!");
    }

    MultipartEntityBuilder b = MultipartEntityBuilder.create();

    // add auth part to the multipart entity
    auth = StringUtils.trimToNull(auth);
    if (auth != null) {
        //StringBody authPart = new StringBody(
        //  auth, ContentType.create( "text/plain", getEncoding() ) );
        //b.addPart( "auth", authPart );
        b.addTextBody("auth", auth, ContentType.create("text/plain", getEncoding()));
    }

    // add file part to the multipart entity
    if (input != null) {
        fileName = StringUtils.trimToNull(fileName);
        if (fileName == null)
            fileName = "upload.bin";
        //InputStreamBody filePart = new InputStreamBody( input, fileName );
        InputStreamBody filePart = new InputStreamBodyWithLength(input, fileName, fileSize);
        b.addPart("videofile", filePart);
    }

    // add multipart entity to the request
    HttpEntity requestMultipartEntity = b.build();
    request.setHeader("MIME-Version", "1.0");
    request.addHeader(requestMultipartEntity.getContentType());
    request.setHeader("Content-Language", "en-US");
    request.setHeader("Accept-Charset", "UTF-8");
    request.setHeader("Accept-Encoding", "gzip,deflate");
    request.setHeader("Connection", "close");
    ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity);

    // sign request
    //getAuthConsumer().sign( request );

    // send request
    HttpResponse response = httpClient.execute(request);

    // create response
    return createResponse(response);
}