Example usage for org.apache.commons.httpclient.methods InputStreamRequestEntity InputStreamRequestEntity

List of usage examples for org.apache.commons.httpclient.methods InputStreamRequestEntity InputStreamRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods InputStreamRequestEntity InputStreamRequestEntity.

Prototype

public InputStreamRequestEntity(InputStream paramInputStream, String paramString) 

Source Link

Usage

From source file:com.panet.imeta.trans.steps.httppost.HTTPPOST.java

private Object[] callHTTPPOST(Object[] rowData) throws KettleException {
    // get dynamic url ?
    if (meta.isUrlInField())
        data.realUrl = data.inputRowMeta.getString(rowData, data.indexOfUrlField);

    try {//from w  ww.ja  va2 s .  c om
        if (log.isDetailed())
            logDetailed(Messages.getString("HTTPPOST.Log.ConnectingToURL", data.realUrl));

        // Prepare HTTP POST
        // 
        HttpClient HTTPPOSTclient = new HttpClient();
        PostMethod post = new PostMethod(data.realUrl);
        //post.setFollowRedirects(false); 

        // Specify content type and encoding
        // If content encoding is not explicitly specified
        // ISO-8859-1 is assumed
        if (Const.isEmpty(data.realEncoding))
            post.setRequestHeader("Content-type", "text/xml");
        else
            post.setRequestHeader("Content-type", "text/xml; " + data.realEncoding);

        // BODY PARAMETERS
        if (data.useBodyParameters) {
            // set body parameters that we want to send 
            for (int i = 0; i < data.body_parameters_nrs.length; i++) {
                data.bodyParameters[i]
                        .setValue(data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i]));
            }
            post.setRequestBody(data.bodyParameters);
        }

        // QUERY PARAMETERS
        if (data.useQueryParameters) {
            for (int i = 0; i < data.query_parameters_nrs.length; i++) {
                data.queryParameters[i]
                        .setValue(data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i]));
            }
            post.setQueryString(data.queryParameters);
        }

        // Set request entity?
        if (data.indexOfRequestEntity >= 0) {
            String tmp = data.inputRowMeta.getString(rowData, data.indexOfRequestEntity);
            // Request content will be retrieved directly
            // from the input stream
            // Per default, the request content needs to be buffered
            // in order to determine its length.
            // Request body buffering can be avoided when
            // content length is explicitly specified

            if (meta.isPostAFile()) {
                File input = new File(tmp);
                post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
            } else {
                post.setRequestEntity(
                        new InputStreamRequestEntity(new ByteArrayInputStream(tmp.getBytes()), tmp.length()));
            }
        }

        // Execute request
        // 
        InputStream inputStream = null;
        try {
            // Execute the POST method
            int statusCode = HTTPPOSTclient.executeMethod(post);

            // Display status code
            if (log.isDebug())
                log.logDebug(toString(), Messages.getString("HTTPPOST.Log.ResponseCode", "" + statusCode));
            String body = null;
            if (statusCode != -1) {
                // the response
                inputStream = post.getResponseBodyAsStream();
                StringBuffer bodyBuffer = new StringBuffer();
                int c;
                while ((c = inputStream.read()) != -1)
                    bodyBuffer.append((char) c);
                inputStream.close();

                // Display response
                body = bodyBuffer.toString();

                if (log.isDebug())
                    log.logDebug(toString(), Messages.getString("HTTPPOST.Log.ResponseBody", body));
            }
            //return new Value(meta.getFieldName(), body);
            return RowDataUtil.addValueData(rowData, data.inputRowMeta.size(), body);
        } finally {
            if (inputStream != null)
                inputStream.close();
            // Release current connection to the connection pool once you are done
            post.releaseConnection();
        }
    } catch (Exception e) {
        throw new KettleException(Messages.getString("HTTPPOST.Error.CanNotReadURL", data.realUrl), e);

    }
}

From source file:com.epam.wilma.gepard.testclient.MultiStubHttpPostRequestSender.java

private void createRequest(final MultiStubRequestParameters requestParameters, final PostMethod httpPost)
        throws IOException, ParserConfigurationException, SAXException {
    InputStream inputStream = requestParameters.getInputStream();
    if (requestParameters.getContentType().contains("fastinfoset")) {
        inputStream = fastInfosetCompressor.compress(inputStream);
    }/*from w w w  .  ja va  2  s . c o  m*/
    if (requestParameters.getContentEncoding().contains("gzip")) {
        inputStream = gzipCompressor.compress(inputStream);
        httpPost.setRequestHeader("Content-Encoding", requestParameters.getContentEncoding());
    }
    final InputStreamRequestEntity entity = new InputStreamRequestEntity(inputStream,
            requestParameters.getContentType());
    httpPost.setRequestEntity(entity);
    httpPost.setRequestHeader("Accept", requestParameters.getAcceptHeader());
    httpPost.addRequestHeader("Accept-Encoding", requestParameters.getAcceptEncoding());
    if (requestParameters.getSpecialHeader() != null) {
        httpPost.addRequestHeader("Special-Header", requestParameters.getSpecialHeader());
    }
    httpPost.addParameter("nextstatus", requestParameters.getStatus());
    httpPost.addParameter("direction", requestParameters.getDirection());
    httpPost.addParameter("groupname", requestParameters.getGroupName());
}

From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.TunnelServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;/*  w w w  . ja v  a  2 s.  co  m*/

    ExtendedHttpMethod postMethod;

    // for this create ui server and port, properties.
    InetSocketAddress inetAddress = new InetSocketAddress(sslEndPoint, sslPort);
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        postMethod = new ExtendedGetMethod();
    else
        postMethod = new ExtendedPostMethod();

    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getRemoteHost());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setTargetURL(this.prot + inetAddress.getHostName());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // copy headers
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if ("host".equals(lhdr)) {
            Enumeration<?> vals = httpRequest.getHeaders(hdr);
            while (vals.hasMoreElements()) {
                String val = (String) vals.nextElement();
                if (val.startsWith("127.0.0.1")) {
                    postMethod.addRequestHeader(hdr, sslEndPoint);
                }
            }
            continue;
        }

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                postMethod.addRequestHeader(hdr, val);
            }
        }

    }

    if (postMethod instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) postMethod)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    httpRequest.getProtocol();
    hostConfiguration.getParams().setParameter(SoapUIHostConfiguration.SOAPUI_SSL_CONFIG,
            settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPATH, "") + " "
                    + settings.getString(SecurityTabForm.SSLTUNNEL_KEYSTOREPASSWORD, ""));
    hostConfiguration.setHost(new URI(this.prot + sslEndPoint, true));

    hostConfiguration = ProxyUtils.initProxySettings(settings, httpState, hostConfiguration, prot + sslEndPoint,
            new DefaultPropertyExpansionContext(project));

    if (sslEndPoint.indexOf("/") < 0)
        postMethod.setPath("/");
    else
        postMethod.setPath(sslEndPoint.substring(sslEndPoint.indexOf("/"), sslEndPoint.length()));

    monitor.fireBeforeProxy(request, response, postMethod, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod);
    }
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(postMethod.getResponseBody());
    capturedData.setResponseHeader(postMethod);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), postMethod, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), postMethod, capturedData.getRawResponseBody()));

    monitor.fireAfterProxy(request, response, postMethod, capturedData);

    StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
    // copy headers to response
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    for (String name : responseHeaders.keySet()) {
        for (String header : responseHeaders.get(name))
            httpResponse.addHeader(name, header);

    }

    IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());

    postMethod.releaseConnection();

    synchronized (this) {
        monitor.addMessageExchange(capturedData);
    }

    capturedData = null;
}

From source file:com.epam.wilma.gepard.testclient.HttpPostRequestSender.java

private void createRequest(final RequestParameters requestParameters, final PostMethod httpPost)
        throws IOException, ParserConfigurationException, SAXException {
    InputStream inputStream = requestParameters.getInputStream();
    if (requestParameters.getContentType().contains("fastinfoset")) {
        inputStream = fastInfosetCompressor.compress(inputStream);
    }//w w  w .jav  a  2 s  .  c o  m
    if (requestParameters.getContentEncoding().contains("gzip")) {
        inputStream = gzipCompressor.compress(inputStream);
        httpPost.setRequestHeader("Content-Encoding", requestParameters.getContentEncoding());
    }
    final InputStreamRequestEntity entity = new InputStreamRequestEntity(inputStream,
            requestParameters.getContentType());
    httpPost.setRequestEntity(entity);
    httpPost.setRequestHeader("Accept", requestParameters.getAcceptHeader());
    httpPost.addRequestHeader("Accept-Encoding", requestParameters.getAcceptEncoding());
    if (requestParameters.getSpecialHeader() != null) {
        httpPost.addRequestHeader("Special-Header", requestParameters.getSpecialHeader());
    }
    for (Entry<String, String> header : requestParameters.getCustomHeaders()) {
        httpPost.addRequestHeader(header.getKey(), header.getValue());
    }
}

From source file:ke.go.moh.oec.adt.Daemon.java

private static boolean sendMessage(String url, String filename) {
    int returnStatus = HttpStatus.SC_CREATED;
    HttpClient httpclient = new HttpClient();
    HttpConnectionManager connectionManager = httpclient.getHttpConnectionManager();
    connectionManager.getParams().setSoTimeout(120000);

    PostMethod httpPost = new PostMethod(url);

    RequestEntity requestEntity;// www .  ja  va  2  s  .  c  o  m
    try {
        FileInputStream message = new FileInputStream(filename);
        Base64InputStream message64 = new Base64InputStream(message, true, -1, null);
        requestEntity = new InputStreamRequestEntity(message64, "application/octet-stream");
    } catch (FileNotFoundException e) {
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "File not found.", e);
        return false;
    }
    httpPost.setRequestEntity(requestEntity);
    try {
        httpclient.executeMethod(httpPost);
        returnStatus = httpPost.getStatusCode();
    } catch (SocketTimeoutException e) {
        returnStatus = HttpStatus.SC_REQUEST_TIMEOUT;
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Request timed out.  Not retrying.", e);
    } catch (HttpException e) {
        returnStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "HTTP exception.  Not retrying.", e);
    } catch (ConnectException e) {
        returnStatus = HttpStatus.SC_SERVICE_UNAVAILABLE;
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Service unavailable.  Not retrying.", e);
    } catch (UnknownHostException e) {
        returnStatus = HttpStatus.SC_NOT_FOUND;
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Not found.  Not retrying.", e);
    } catch (IOException e) {
        returnStatus = HttpStatus.SC_GATEWAY_TIMEOUT;
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "IO exception.  Not retrying.", e);
    } finally {
        httpPost.releaseConnection();
    }
    return returnStatus == HttpStatus.SC_OK;
}

From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.ProxyServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;/* ww w .j  a  v a 2 s. c  o m*/

    ExtendedHttpMethod method;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        method = new ExtendedGetMethod();
    else
        method = new ExtendedPostMethod();

    method.setDecompress(false);

    // for this create ui server and port, properties.
    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getServerName());
    capturedData.setRequestMethod(httpRequest.getMethod());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setHttpRequestParameters(httpRequest);
    capturedData.setTargetURL(httpRequest.getRequestURL().toString());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // check connection header
    String connectionHeader = httpRequest.getHeader("Connection");
    if (connectionHeader != null) {
        connectionHeader = connectionHeader.toLowerCase();
        if (connectionHeader.indexOf("keep-alive") < 0 && connectionHeader.indexOf("close") < 0)
            connectionHeader = null;
    }

    // copy headers
    boolean xForwardedFor = false;
    @SuppressWarnings("unused")
    long contentLength = -1;
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if (dontProxyHeaders.contains(lhdr))
            continue;
        if (connectionHeader != null && connectionHeader.indexOf(lhdr) >= 0)
            continue;

        if ("content-length".equals(lhdr))
            contentLength = request.getContentLength();

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                method.setRequestHeader(lhdr, val);
                xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
            }
        }
    }

    // Proxy headers
    method.setRequestHeader("Via", "SoapUI Monitor");
    if (!xForwardedFor)
        method.addRequestHeader("X-Forwarded-For", request.getRemoteAddr());

    if (method instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) method)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    StringBuffer url = new StringBuffer("http://");
    url.append(httpRequest.getServerName());
    if (httpRequest.getServerPort() != 80)
        url.append(":" + httpRequest.getServerPort());
    if (httpRequest.getServletPath() != null) {
        url.append(httpRequest.getServletPath());
        method.setPath(httpRequest.getServletPath());
        if (httpRequest.getQueryString() != null) {
            url.append("?" + httpRequest.getQueryString());
            method.setPath(httpRequest.getServletPath() + "?" + httpRequest.getQueryString());
        }
    }
    hostConfiguration.setHost(new URI(url.toString(), true));

    // SoapUI.log("PROXY to:" + url);

    monitor.fireBeforeProxy(request, response, method, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method);
    }

    // wait for transaction to end and store it.
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(method.getResponseBody());
    capturedData.setResponseHeader(method);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), method, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), method, capturedData.getRawResponseBody()));
    capturedData.setResponseContent(new String(method.getDecompressedResponseBody()));

    monitor.fireAfterProxy(request, response, method, capturedData);

    if (!response.isCommitted()) {
        StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
        // capturedData = null;

        // copy headers to response
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        for (String name : responseHeaders.keySet()) {
            for (String header : responseHeaders.get(name))
                httpResponse.addHeader(name, header);
        }

        IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());
    }

    synchronized (this) {
        if (checkContentType(method)) {
            monitor.addMessageExchange(capturedData);
        }
    }
}

From source file:edu.caltech.ipac.firefly.server.WorkspaceManager.java

public boolean davPut(File upload, String toPath) {
    try {/*from   w w w .  j av a 2  s  . c o  m*/
        PutMethod put = new PutMethod(getResourceUrl(toPath));
        RequestEntity requestEntity = new InputStreamRequestEntity(
                new BufferedInputStream(new FileInputStream(upload), HttpServices.BUFFER_SIZE),
                upload.length());
        put.setRequestEntity(requestEntity);
        /** is to allow a client that is sending a request message with a request body
         *  to determine if the origin server is willing to accept the request
         * (based on the request headers) before the client sends the request body.
         * this require server supporting HTTP/1.1 protocol.
         */
        put.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

        if (!executeMethod(put)) {
            // handle error
            System.out.println("Unable to upload file:" + toPath + " -- " + put.getStatusText());
            return false;
        }

        return true;
    } catch (Exception e) {
        LOG.error(e, "Error while uploading file:" + upload.getPath());
    }
    return false;
}

From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;//from w  w w .j a va2  s .  com
    }
    if (!servletRequest.isUserInRole("HOPS_ADMIN")) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this service");
        return;
    }
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    // note: we won't transfer the protocol version because I'm not 
    // sure it would truly be compatible
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);

    try {
        // Execute the request

        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);
        HostConfiguration config = new HostConfiguration();
        InetAddress localAddress = InetAddress.getLocalHost();
        config.setLocalAddress(localAddress);

        String method = servletRequest.getMethod();
        HttpMethod m;
        if (method.equalsIgnoreCase("PUT")) {
            m = new PutMethod(proxyRequestUri);
            RequestEntity requestEntity = new InputStreamRequestEntity(servletRequest.getInputStream(),
                    servletRequest.getContentType());
            ((PutMethod) m).setRequestEntity(requestEntity);
        } else {
            m = new GetMethod(proxyRequestUri);
        }
        Enumeration<String> names = servletRequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String headerName = names.nextElement();
            String value = servletRequest.getHeader(headerName);
            if (PASS_THROUGH_HEADERS.contains(headerName)) {
                //yarn does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null
                        || !servletRequest.getPathInfo().contains(".js"))) {
                    continue;
                } else {
                    m.setRequestHeader(headerName, value);
                }
            }
        }
        String user = servletRequest.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(config, m);

        // Process the response
        int statusCode = m.getStatusCode();

        // Pass the response code. This method with the "reason phrase" is 
        //deprecated but it's the only way to pass the reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase());

        copyResponseHeaders(m, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(m, servletResponse);

    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    }
}

From source file:com.simonellistonball.nifi.processors.OpenScoringProcessor.OpenScoringProcessor.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();//from   www .ja  va2  s . c o m
    if (flowFile == null) {
        return;
    }

    if (id.get() == null) {
        try {
            this.id.set(postModel(context.getProperty(OPENSCORING_URL).getValue(),
                    context.getProperty(PMML).getValue()));
        } catch (IOException e) {
            getLogger().error("Failure to post model", e);
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, FAILURE_MODEL);
        }
    }

    final String openScoringUrl = context.getProperty(OPENSCORING_URL).getValue();

    try {
        final boolean isCsv = flowFile.getAttribute("mime.type") == "text/csv";

        StringBuilder urlBuilder = new StringBuilder(openScoringUrl).append("/model/").append(id);
        if (isCsv) {
            urlBuilder.append("/csv");
        }
        final PostMethod post = new PostMethod(urlBuilder.toString());

        final String contentType;
        if (isCsv) {
            contentType = "text/plain";
        } else {
            contentType = "application/json";
        }
        post.setRequestHeader("Content-Type", contentType);

        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream in) throws IOException {
                post.setRequestEntity(new InputStreamRequestEntity(in, contentType));
            }
        });

        httpClient.executeMethod(post);
        if (isCsv) {
            // add the results to the input
            flowFile = session.write(flowFile, new OutputStreamCallback() {
                @Override
                public void process(OutputStream out) throws IOException {
                    IOUtils.copy(post.getResponseBodyAsStream(), out);
                }
            });
            session.transfer(flowFile, SUCCESS);
        } else {
            JsonParser parser = new JsonParser();
            JsonElement parsed = parser
                    .parse(new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), "UTF-8")));

            JsonObject newAttributes = parsed.getAsJsonObject().getAsJsonObject("result");
            final Map<String, String> attributes = new HashMap<String, String>(newAttributes.size());

            for (Entry<String, JsonElement> attribute : newAttributes.entrySet()) {
                if (!attribute.getValue().isJsonNull()) {
                    attributes.put(attribute.getKey(), attribute.getValue().getAsString());
                }
            }

            if (!attributes.isEmpty()) {
                flowFile = session.putAllAttributes(flowFile, attributes);
            }
            session.transfer(flowFile, SUCCESS);
        }
    } catch (Exception e) {
        getLogger().error("Failure to score model", e);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, FAILURE);
    }

}

From source file:com.zimbra.qa.unittest.TestUserServlet.java

/**
 * Test that can import into a new calendar from ICALENDAR containing an inline ATTACHment.
 * Test that it is possible to export calendar entry with an attachment with the attachment
 * inlined if icalAttach=inline or ignoring the attachment if icalAttach=none
 *///from ww w  . ja  v a2 s .c  om
public void testIcsImportExport() throws IOException, ValidationException, ServiceException {
    ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
    String calName = NAME_PREFIX + "2ndCalendar";
    String calUri = String.format("/%s?fmt=ics", calName);
    TestUtil.createFolder(mbox, calName, ZFolder.View.appointment);
    net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();
    calendar.getProperties().add(new ProdId("-//ZimbraTest 1.0//EN"));
    calendar.getProperties().add(Version.VERSION_2_0);
    calendar.getProperties().add(CalScale.GREGORIAN);
    java.util.Calendar start = java.util.Calendar.getInstance();
    start.set(java.util.Calendar.MONTH, java.util.Calendar.SEPTEMBER);
    start.set(java.util.Calendar.DAY_OF_MONTH, 03);

    VEvent wwII = new VEvent(new Date(start.getTime()), NAME_PREFIX + " Declarations of war");
    wwII.getProperties().getProperty(Property.DTSTART).getParameters().add(Value.DATE);
    wwII.getProperties().add(new Uid("3-14159"));
    Attach attach = new Attach("Attachment.\nIsn't it short.".getBytes(MimeConstants.P_CHARSET_ASCII));
    attach.getParameters().add(new XParameter("X-APPLE-FILENAME", "short.txt"));
    attach.getParameters().add(new FmtType(MimeConstants.CT_TEXT_PLAIN));
    wwII.getProperties().add(attach);
    calendar.getComponents().add(wwII);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    CalendarOutputter outputter = new CalendarOutputter();
    outputter.setValidating(false);
    outputter.output(calendar, buf);
    URI uri = mbox.getRestURI(calUri);
    HttpClient client = mbox.getHttpClient(uri);
    PostMethod post = new PostMethod(uri.toString());
    post.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(buf.toByteArray()),
            MimeConstants.CT_TEXT_CALENDAR));
    ZimbraLog.test.info("testIcsImportExport:ICS to be imported:%s", new String(buf.toByteArray()));
    TestCalDav.HttpMethodExecutor.execute(client, post, HttpStatus.SC_OK);
    uri = mbox.getRestURI(calUri + "&icalAttach=inline");
    GetMethod get = new GetMethod(uri.toString());
    TestCalDav.HttpMethodExecutor executor = new TestCalDav.HttpMethodExecutor(client, get, HttpStatus.SC_OK);
    String respIcal = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    ZimbraLog.test.info("testIcsImportExport:ICS exported (with icalAttach=inline):%s", respIcal);
    int attachNdx = respIcal.indexOf("ATTACH;");
    assertTrue("ATTACH should be present", -1 != attachNdx);
    String fromAttach = respIcal.substring(attachNdx);
    assertTrue("BINARY should be present", -1 != fromAttach.indexOf("VALUE=BINARY"));
    uri = mbox.getRestURI(calUri + "&icalAttach=none");
    get = new GetMethod(uri.toString());
    executor = new TestCalDav.HttpMethodExecutor(client, get, HttpStatus.SC_OK);
    respIcal = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    ZimbraLog.test.debug("testIcsImportExport:ICS exported (with icalAttach=none):%s", respIcal);
    assertTrue("ATTACH should be present", -1 == respIcal.indexOf("ATTACH;"));
    uri = mbox.getRestURI(calUri);
    get = new GetMethod(uri.toString());
    executor = new TestCalDav.HttpMethodExecutor(client, get, HttpStatus.SC_OK);
    respIcal = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    ZimbraLog.test.debug("testIcsImportExport:ICS exported (default - same as icalAttach=none):%s", respIcal);
    assertTrue("ATTACH should be present", -1 == respIcal.indexOf("ATTACH;"));
}