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

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

Introduction

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

Prototype

public static MultipartEntityBuilder create() 

Source Link

Usage

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**/*  w  w w  .j  a  va  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:hello.MyPostHTTP.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {

    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(
            context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setConnectTimeout(
            context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    requestConfigBuilder.setRedirectsEnabled(false);
    requestConfigBuilder//w  ww .jav  a2 s. c o  m
            .setSocketTimeout(context.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    final RequestConfig requestConfig = requestConfigBuilder.build();

    final StreamThrottler throttler = throttlerRef.get();
    final ProcessorLog logger = getLogger();

    String lastUrl = null;
    long bytesToSend = 0L;

    final List<FlowFile> toSend = new ArrayList<>();
    CloseableHttpClient client = null;
    final String transactionId = UUID.randomUUID().toString();

    final ObjectHolder<String> dnHolder = new ObjectHolder<>("none");
    while (true) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            break;
        }

        final String url = context.getProperty(URL).evaluateAttributeExpressions(flowFile).getValue();
        try {
            new java.net.URL(url);
        } catch (final MalformedURLException e) {
            logger.error(
                    "After substituting attribute values for {}, URL is {}; this is not a valid URL, so routing to failure",
                    new Object[] { flowFile, url });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            continue;
        }

        // If this FlowFile doesn't have the same url, throw it back on the queue and stop grabbing FlowFiles
        if (lastUrl != null && !lastUrl.equals(url)) {
            session.transfer(flowFile);
            break;
        }

        lastUrl = url;
        toSend.add(flowFile);

        if (client == null) {
            final Config config = getConfig(url, context);
            final HttpClientConnectionManager conMan = config.getConnectionManager();

            final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            clientBuilder.setConnectionManager(conMan);
            clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
                @Override
                public void process(final HttpResponse response, final HttpContext httpContext)
                        throws HttpException, IOException {
                    final HttpCoreContext coreContext = HttpCoreContext.adapt(httpContext);
                    final ManagedHttpClientConnection conn = coreContext
                            .getConnection(ManagedHttpClientConnection.class);
                    if (!conn.isOpen()) {
                        return;
                    }

                    final SSLSession sslSession = conn.getSSLSession();

                    if (sslSession != null) {
                        final X509Certificate[] certChain = sslSession.getPeerCertificateChain();
                        if (certChain == null || certChain.length == 0) {
                            throw new SSLPeerUnverifiedException("No certificates found");
                        }

                        final X509Certificate cert = certChain[0];
                        dnHolder.set(cert.getSubjectDN().getName().trim());
                    }
                }
            });

            clientBuilder.disableAutomaticRetries();
            clientBuilder.disableContentCompression();

            client = clientBuilder.build();
        }

        bytesToSend += flowFile.getSize();
        break;
    }

    if (toSend.isEmpty()) {
        return;
    }

    final String url = lastUrl;
    final HttpPost post = new HttpPost(url);
    final List<FlowFile> flowFileList = toSend;

    String userName = "Chris";
    String password = "password";
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("userName", userName);
    builder.addTextBody("password", password);
    for (final FlowFile flowFile : flowFileList) {
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(final InputStream rawIn) throws IOException {
                InputStream in = new ByteArrayInputStream(IOUtils.toByteArray(rawIn));
                builder.addBinaryBody("file", in, ContentType.DEFAULT_BINARY, "filename");
            }
        });
    }

    final HttpEntity entity2 = builder.build();

    post.setEntity(entity2);
    post.setConfig(requestConfig);

    final String contentType;

    contentType = DEFAULT_CONTENT_TYPE;
    post.setHeader(CONTENT_TYPE_HEADER, contentType);
    post.setHeader(FLOWFILE_CONFIRMATION_HEADER, "true");
    post.setHeader(PROTOCOL_VERSION_HEADER, PROTOCOL_VERSION);
    post.setHeader(TRANSACTION_ID_HEADER, transactionId);

    // Do the actual POST
    final String flowFileDescription = toSend.size() <= 10 ? toSend.toString() : toSend.size() + " FlowFiles";

    final String uploadDataRate;
    final long uploadMillis;
    CloseableHttpResponse response = null;
    try {
        final StopWatch stopWatch = new StopWatch(true);
        response = client.execute(post);
        // consume input stream entirely, ignoring its contents. If we
        // don't do this, the Connection will not be returned to the pool
        EntityUtils.consume(response.getEntity());
        stopWatch.stop();
        uploadDataRate = stopWatch.calculateDataRate(bytesToSend);
        uploadMillis = stopWatch.getDuration(TimeUnit.MILLISECONDS);
    } catch (final IOException e) {
        logger.error("Failed to Post {} due to {}; transferring to failure",
                new Object[] { flowFileDescription, e });
        context.yield();
        for (FlowFile flowFile : toSend) {
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
        }
        return;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (final IOException e) {
                getLogger().warn("Failed to close HTTP Response due to {}", new Object[] { e });
            }
        }
    }

    // If we get a 'SEE OTHER' status code and an HTTP header that indicates that the intent
    // of the Location URI is a flowfile hold, we will store this holdUri. This prevents us
    // from posting to some other webservice and then attempting to delete some resource to which
    // we are redirected
    final int responseCode = response.getStatusLine().getStatusCode();
    final String responseReason = response.getStatusLine().getReasonPhrase();
    String holdUri = null;
    if (responseCode == HttpServletResponse.SC_SEE_OTHER) {
        final Header locationUriHeader = response.getFirstHeader(LOCATION_URI_INTENT_NAME);
        if (locationUriHeader != null) {
            if (LOCATION_URI_INTENT_VALUE.equals(locationUriHeader.getValue())) {
                final Header holdUriHeader = response.getFirstHeader(LOCATION_HEADER_NAME);
                if (holdUriHeader != null) {
                    holdUri = holdUriHeader.getValue();
                }
            }
        }

        if (holdUri == null) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: sent content and received status code {}:{} but no Hold URI",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }

    if (holdUri == null) {
        if (responseCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error(
                        "Failed to Post {} to {}: response code was {}:{}; will yield processing, "
                                + "since the destination is temporarily unavailable",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            context.yield();
            return;
        }

        if (responseCode >= 300) {
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                logger.error("Failed to Post {} to {}: response code was {}:{}",
                        new Object[] { flowFile, url, responseCode, responseReason });
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }

        logger.info("Successfully Posted {} to {} in {} at a rate of {}", new Object[] { flowFileDescription,
                url, FormatUtils.formatMinutesSeconds(uploadMillis, TimeUnit.MILLISECONDS), uploadDataRate });

        for (final FlowFile flowFile : toSend) {
            session.getProvenanceReporter().send(flowFile, url, "Remote DN=" + dnHolder.get(), uploadMillis,
                    true);
            session.transfer(flowFile, REL_SUCCESS);
        }
        return;
    }

    //
    // the response indicated a Hold URI; delete the Hold.
    //
    // determine the full URI of the Flow File's Hold; Unfortunately, the responses that are returned have
    // changed over the past, so we have to take into account a few different possibilities.
    String fullHoldUri = holdUri;
    if (holdUri.startsWith("/contentListener")) {
        // If the Hold URI that we get starts with /contentListener, it may not really be /contentListener,
        // as this really indicates that it should be whatever we posted to -- if posting directly to the
        // ListenHTTP component, it will be /contentListener, but if posting to a proxy/load balancer, we may
        // be posting to some other URL.
        fullHoldUri = url + holdUri.substring(16);
    } else if (holdUri.startsWith("/")) {
        // URL indicates the full path but not hostname or port; use the same hostname & port that we posted
        // to but use the full path indicated by the response.
        int firstSlash = url.indexOf("/", 8);
        if (firstSlash < 0) {
            firstSlash = url.length();
        }
        final String beforeSlash = url.substring(0, firstSlash);
        fullHoldUri = beforeSlash + holdUri;
    } else if (!holdUri.startsWith("http")) {
        // Absolute URL
        fullHoldUri = url + (url.endsWith("/") ? "" : "/") + holdUri;
    }

    final HttpDelete delete = new HttpDelete(fullHoldUri);
    delete.setHeader(TRANSACTION_ID_HEADER, transactionId);

    while (true) {
        try {
            final HttpResponse holdResponse = client.execute(delete);
            EntityUtils.consume(holdResponse.getEntity());
            final int holdStatusCode = holdResponse.getStatusLine().getStatusCode();
            final String holdReason = holdResponse.getStatusLine().getReasonPhrase();
            if (holdStatusCode >= 300) {
                logger.error(
                        "Failed to delete Hold that destination placed on {}: got response code {}:{}; routing to failure",
                        new Object[] { flowFileDescription, holdStatusCode, holdReason });

                for (FlowFile flowFile : toSend) {
                    flowFile = session.penalize(flowFile);
                    session.transfer(flowFile, REL_FAILURE);
                }
                return;
            }

            logger.info("Successfully Posted {} to {} in {} milliseconds at a rate of {}",
                    new Object[] { flowFileDescription, url, uploadMillis, uploadDataRate });

            for (final FlowFile flowFile : toSend) {
                session.getProvenanceReporter().send(flowFile, url);
                session.transfer(flowFile, REL_SUCCESS);
            }
            return;
        } catch (final IOException e) {
            logger.warn("Failed to delete Hold that destination placed on {} due to {}",
                    new Object[] { flowFileDescription, e });
        }

        if (!isScheduled()) {
            context.yield();
            logger.warn(
                    "Failed to delete Hold that destination placed on {}; Processor has been stopped so routing FlowFile(s) to failure",
                    new Object[] { flowFileDescription });
            for (FlowFile flowFile : toSend) {
                flowFile = session.penalize(flowFile);
                session.transfer(flowFile, REL_FAILURE);
            }
            return;
        }
    }
}

From source file:io.swagger.client.api.DefaultApi.java

/**
 * One-shot movie scene//from   w w  w .ja v  a2 s .  co m
 * Retrieves the current list of cards related to the given movie scene
 * @param authorization Authorization token (&#39;Bearer &lt;token&gt;&#39;)
 * @param clientMovieId Client movie ID being played
 * @param timestamp Current movie timestamp in seconds
 * @param acceptLanguage Client locale, as &lt;language&gt;-&lt;country&gt;
 * @param contentType application/json
 * @param relations Indicates if the received scene cards should contain the scene hierarchy (true) or be a flat list of the main scene items (false)
 * @param imageSize Size of the images returned in the response
 * @return List<Card>
 */
public List<Card> getStaticMovieScene(String authorization, String clientMovieId, Float timestamp,
        String acceptLanguage, String contentType, Boolean relations, String imageSize) throws ApiException {
    Object localVarPostBody = null;

    // verify the required parameter 'authorization' is set
    if (authorization == null) {
        throw new ApiException(400,
                "Missing the required parameter 'authorization' when calling getStaticMovieScene");
    }

    // verify the required parameter 'clientMovieId' is set
    if (clientMovieId == null) {
        throw new ApiException(400,
                "Missing the required parameter 'clientMovieId' when calling getStaticMovieScene");
    }

    // verify the required parameter 'timestamp' is set
    if (timestamp == null) {
        throw new ApiException(400,
                "Missing the required parameter 'timestamp' when calling getStaticMovieScene");
    }

    // create path and map variables
    String localVarPath = "/movies/{client_movie_id}/static/{timestamp}".replaceAll("\\{format\\}", "json")
            .replaceAll("\\{" + "client_movie_id" + "\\}", apiInvoker.escapeString(clientMovieId.toString()))
            .replaceAll("\\{" + "timestamp" + "\\}", apiInvoker.escapeString(timestamp.toString()));

    // query params
    List<Pair> localVarQueryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> localVarHeaderParams = new HashMap<String, String>();
    // form params
    Map<String, String> localVarFormParams = new HashMap<String, String>();

    localVarQueryParams.addAll(ApiInvoker.parameterToPairs("", "relations", relations));
    localVarQueryParams.addAll(ApiInvoker.parameterToPairs("", "image_size", imageSize));

    localVarHeaderParams.put("Authorization", ApiInvoker.parameterToString(authorization));
    localVarHeaderParams.put("Accept-Language", ApiInvoker.parameterToString(acceptLanguage));
    localVarHeaderParams.put("Content-Type", ApiInvoker.parameterToString(contentType));

    String[] localVarContentTypes = { "application/json" };
    String localVarContentType = localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json";

    if (localVarContentType.startsWith("multipart/form-data")) {
        // file uploading
        MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

        localVarPostBody = localVarBuilder.build();
    } else {
        // normal form params
    }

    try {
        String localVarResponse = apiInvoker.invokeAPI(basePath, localVarPath, "GET", localVarQueryParams,
                localVarPostBody, localVarHeaderParams, localVarFormParams, localVarContentType);
        if (localVarResponse != null) {
            return (List<Card>) ApiInvoker.deserialize(localVarResponse, "array", Card.class);
        } else {
            return null;
        }
    } catch (ApiException ex) {
        throw ex;
    }
}

From source file:com.basistech.rosette.api.HttpRosetteAPI.java

private void setupMultipartRequest(final Request request, final ObjectWriter finalWriter, HttpPost post)
        throws IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMimeSubtype("mixed");
    builder.setMode(HttpMultipartMode.STRICT);

    FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("request",
            // Make sure we're not mislead by someone who puts a charset into the mime type.
            new AbstractContentBody(ContentType.parse(ContentType.APPLICATION_JSON.getMimeType())) {
                @Override//from   w  w  w .j a v  a2  s  .c om
                public String getFilename() {
                    return null;
                }

                @Override
                public void writeTo(OutputStream out) throws IOException {
                    finalWriter.writeValue(out, request);
                }

                @Override
                public String getTransferEncoding() {
                    return MIME.ENC_BINARY;
                }

                @Override
                public long getContentLength() {
                    return -1;
                }
            });

    // Either one of 'name=' or 'Content-ID' would be enough.
    partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"request\"");
    partBuilder.setField("Content-ID", "request");

    builder.addPart(partBuilder.build());

    AbstractContentBody insBody;
    if (request instanceof DocumentRequest) {
        DocumentRequest docReq = (DocumentRequest) request;
        insBody = new InputStreamBody(docReq.getContentBytes(), ContentType.parse(docReq.getContentType()));
    } else if (request instanceof AdmRequest) {
        //TODO: smile?
        AdmRequest admReq = (AdmRequest) request;
        ObjectWriter writer = mapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
        byte[] json = writer.writeValueAsBytes(admReq.getText());
        insBody = new ByteArrayBody(json, ContentType.parse(AdmRequest.ADM_CONTENT_TYPE), null);
    } else {
        throw new UnsupportedOperationException("Unsupported request type for multipart processing");
    }
    partBuilder = FormBodyPartBuilder.create("content", insBody);
    partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"content\"");
    partBuilder.setField("Content-ID", "content");
    builder.addPart(partBuilder.build());
    builder.setCharset(StandardCharsets.UTF_8);
    HttpEntity entity = builder.build();
    post.setEntity(entity);
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

private HttpEntity buildParts(BaseRequest request) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (PartHolder h : TankHttpUtil.getPartsFromBody(request)) {
        if (h.getFileName() == null) {
            if (h.isContentTypeSet()) {
                builder.addTextBody(h.getPartName(), new String(h.getBodyAsString()),
                        ContentType.create(h.getContentType()));
            } else {
                builder.addTextBody(h.getPartName(), new String(h.getBodyAsString()));
            }/*from  ww  w.  ja v  a2s  .  c om*/
        } else {
            if (h.isContentTypeSet()) {
                builder.addBinaryBody(h.getPartName(), h.getBody(), ContentType.create(h.getContentType()),
                        h.getFileName());
            } else {
                builder.addBinaryBody(h.getFileName(), h.getBody());
            }
        }
    }
    return builder.build();
}

From source file:io.swagger.client.api.CameraApi.java

/**
* Stop recording a movie//from w  w w . jav  a 2s.  c  o  m
* 
        
*/
public void captureStopPost(final Response.Listener<String> responseListener,
        final Response.ErrorListener errorListener) {
    Object postBody = null;

    // create path and map variables
    String path = "/capture/stop".replaceAll("\\{format\\}", "json");

    // query params
    List<Pair> queryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> headerParams = new HashMap<String, String>();
    // form params
    Map<String, String> formParams = new HashMap<String, String>();

    String[] contentTypes = {

    };
    String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

    if (contentType.startsWith("multipart/form-data")) {
        // file uploading
        MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

        HttpEntity httpEntity = localVarBuilder.build();
        postBody = httpEntity;
    } else {
        // normal form params
    }

    String[] authNames = new String[] {};

    try {
        apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams,
                contentType, authNames, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String localVarResponse) {
                        responseListener.onResponse(localVarResponse);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        errorListener.onErrorResponse(error);
                    }
                });
    } catch (ApiException ex) {
        errorListener.onErrorResponse(new VolleyError(ex));
    }
}

From source file:sx.blah.discord.handle.impl.obj.Channel.java

@Override
public IMessage sendFiles(String content, boolean tts, EmbedObject embed, AttachmentPartEntry... entries) {
    PermissionUtils.requirePermissions(this, client.getOurUser(), Permissions.SEND_MESSAGES,
            Permissions.ATTACH_FILES);

    try {/*from ww  w .ja va2 s. com*/
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (entries.length == 1) {
            builder.addBinaryBody("file", entries[0].getFileData(), ContentType.APPLICATION_OCTET_STREAM,
                    entries[0].getFileName());
        } else {
            for (int i = 0; i < entries.length; i++) {
                builder.addBinaryBody("file" + i, entries[i].getFileData(),
                        ContentType.APPLICATION_OCTET_STREAM, entries[i].getFileName());
            }
        }

        builder.addTextBody("payload_json",
                DiscordUtils.MAPPER_NO_NULLS.writeValueAsString(new FilePayloadObject(content, tts, embed)),
                ContentType.MULTIPART_FORM_DATA.withCharset("UTF-8"));

        HttpEntity fileEntity = builder.build();
        MessageObject messageObject = DiscordUtils.MAPPER
                .readValue(
                        client.REQUESTS.POST.makeRequest(DiscordEndpoints.CHANNELS + id + "/messages",
                                fileEntity, new BasicNameValuePair("Content-Type", "multipart/form-data")),
                        MessageObject.class);

        return DiscordUtils.getMessageFromJSON(this, messageObject);
    } catch (IOException e) {
        throw new DiscordException("JSON Parsing exception!", e);
    }
}

From source file:com.lgallardo.youtorrentcontroller.JSONParser.java

public void postCommand(String command, String hash) throws JSONParserStatusCodeException {

    String key = "hash";

    String urlContentType = "application/x-www-form-urlencoded";

    String boundary = null;/*from  w w  w . j  a  v a2  s. c  om*/

    StringBuilder fileContent = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    String url = "";

    //        Log.d("Debug", "JSONParser - command: " + command);

    if ("start".equals(command) || "startSelected".equals(command)) {
        url = url + "gui/?action=start&hash=" + hash;
    }

    if ("pause".equals(command) || "pauseSelected".equals(command)) {
        url = url + "gui/?action=pause&hash=" + hash;
    }

    if ("stop".equals(command) || "stopSelected".equals(command)) {
        url = url + "gui/?action=stop&hash=" + hash;
        Log.d("Debug", "Stoping torrent " + hash);
    }

    if ("delete".equals(command) || "deleteSelected".equals(command)) {
        url = url + "gui/?action=remove&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) {
        url = url + "gui/?action=removedata&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("addTorrent".equals(command)) {

        URI hash_uri = null;

        try {
            hash_uri = new URI(hash);
            hash = hash_uri.toString();

            //                Log.d("Debug","Torrent URL: "+ hash);

        } catch (URISyntaxException e) {
            Log.e("Debug", "URISyntaxException: " + e.toString());
        }

        url = url + "gui/?action=add-url&s=" + hash;
        //            key = "urls";
    }

    if ("addTorrentFile".equals(command)) {
        url = url + "gui/?action=add-file";
        key = "urls";

        boundary = "-----------------------" + (new Date()).getTime();

        urlContentType = "multipart/form-data; boundary=" + boundary;
        //            urlContentType = "multipart/form-data";

    }

    //        if ("pauseall".equals(command)) {
    //            url = "command/pauseall";
    //        }
    //
    //        if ("pauseAll".equals(command)) {
    //            url = "command/pauseAll";
    //        }
    //
    //
    //        if ("resumeall".equals(command)) {
    //            url = "command/resumeall";
    //        }
    //
    //        if ("resumeAll".equals(command)) {
    //            url = "command/resumeAll";
    //        }

    if ("increasePrio".equals(command)) {
        url = url + "gui/?action=queueup&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("decreasePrio".equals(command)) {
        url = url + "gui/?action=queuedown&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("maxPrio".equals(command)) {
        url = url + "gui/?action=queuetop&hash=" + hash.replace("|", "&hash=");
        key = "hashes";
    }

    if ("minPrio".equals(command)) {
        url = url + "gui/?action=queuebottom&hash=" + hash.replace("|", "&hash=");
        key = "hashes";

    }

    if ("setQBittorrentPrefefrences".equals(command)) {
        url = "command/setPreferences";
        key = "json";
    }

    if ("recheckSelected".equals(command)) {
        url = url + "gui/?action=recheck&hash=" + hash.replace("|", "&hash=");
    }

    //        if ("toggleFirstLastPiecePrio".equals(command)) {
    //            url = "command/toggleFirstLastPiecePrio";
    //            key = "hashes";
    //
    //        }
    //
    //        if ("toggleSequentialDownload".equals(command)) {
    //            url = "command/toggleSequentialDownload";
    //            key = "hashes";
    //
    //        }

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "youTorrent Controller");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    // Set http parameters
    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url + "&token=" + token;

        //            Log.d("Debug", "JSONParser - url: " + url);

        HttpPost httpget = new HttpPost(url);

        if ("addTorrent".equals(command)) {
            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();
        }

        // In order to pass the has we must set the pair name value
        BasicNameValuePair bnvp = new BasicNameValuePair(key, hash);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(bnvp);

        httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        // Set content type and urls
        if ("increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command)) {
            httpget.setHeader("Content-Type", urlContentType);

        }

        // Set cookie
        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        // Set content type and urls
        if ("addTorrentFile".equals(command)) {

            //                Log.d("Debug", "JSONParser - urlContentType: " +  urlContentType);
            //                Log.d("Debug", "JSONParser - hash: " +  Uri.decode(URLEncoder.encode(hash, "UTF-8")));
            //                Log.d("Debug", "JSONParser - hash: " +  hash);

            httpget.setHeader("Content-Type", urlContentType);

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

            // Add boundary
            builder.setBoundary(boundary);

            // Add torrent file as binary
            File file = new File(hash);
            // FileBody fileBody = new FileBody(file);
            // builder.addPart("file", fileBody);

            builder.addBinaryBody("torrent_file", file, ContentType.DEFAULT_BINARY, null);
            //                builder.addBinaryBody("upfile", file, ContentType.create(urlContentType), hash);

            // Build entity
            HttpEntity entity = builder.build();

            // Set entity to http post
            httpget.setEntity(entity);

        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {

    } catch (ClientProtocolException e) {
        Log.e("Debug", "Client: " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Debug", "IO: " + e.toString());
        // e.printStackTrace();
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:io.swagger.client.api.CameraApi.java

/**
* Camera info/*from  ww w. j  a  v  a  2s  .  c om*/
* Return information about the camera 
 * @return CameraInfo
*/
public CameraInfo infoGet() throws TimeoutException, ExecutionException, InterruptedException, ApiException {
    Object postBody = null;

    // create path and map variables
    String path = "/info".replaceAll("\\{format\\}", "json");

    // query params
    List<Pair> queryParams = new ArrayList<Pair>();
    // header params
    Map<String, String> headerParams = new HashMap<String, String>();
    // form params
    Map<String, String> formParams = new HashMap<String, String>();

    String[] contentTypes = {

    };
    String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

    if (contentType.startsWith("multipart/form-data")) {
        // file uploading
        MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

        HttpEntity httpEntity = localVarBuilder.build();
        postBody = httpEntity;
    } else {
        // normal form params
    }

    String[] authNames = new String[] {};

    try {
        String localVarResponse = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody,
                headerParams, formParams, contentType, authNames);
        if (localVarResponse != null) {
            return (CameraInfo) ApiInvoker.deserialize(localVarResponse, "", CameraInfo.class);
        } else {
            return null;
        }
    } catch (ApiException ex) {
        throw ex;
    } catch (InterruptedException ex) {
        throw ex;
    } catch (ExecutionException ex) {
        if (ex.getCause() instanceof VolleyError) {
            VolleyError volleyError = (VolleyError) ex.getCause();
            if (volleyError.networkResponse != null) {
                throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage());
            }
        }
        throw ex;
    } catch (TimeoutException ex) {
        throw ex;
    }
}