Example usage for org.apache.commons.httpclient.methods PostMethod getRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PostMethod getRequestEntity

Introduction

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

Prototype

public RequestEntity getRequestEntity() 

Source Link

Usage

From source file:com.groupon.jenkins.dotci.notifiers.WebhookNotifierTest.java

@Test
public void should_make_a_post_to_web_hook_url_with_payload() throws HttpException, IOException {

    final HttpClient httpClient = mock(HttpClient.class);
    ImmutableMap<String, String> payload = ImmutableMap.of("option1", "value1");
    final Map<String, Serializable> options = ImmutableMap.of("url", "http://example.com/", "payload", payload);
    WebhookNotifier webhookNotifier = new WebhookNotifier() {
        @Override//from   w  ww .j a  va  2  s. c o m
        protected HttpClient getHttpClient() {
            return httpClient;
        };

        @Override
        public Object getOptions() {
            return options;
        }
    };

    webhookNotifier.notify(null, getMockListener());

    ArgumentCaptor<PostMethod> argument = ArgumentCaptor.forClass(PostMethod.class);
    verify(httpClient).executeMethod(argument.capture());
    PostMethod post = argument.getValue();

    assertEquals("http://example.com/", post.getURI().toString());
    assertEquals("{\"option1\":\"value1\"}", ((StringRequestEntity) post.getRequestEntity()).getContent());

}

From source file:org.alfresco.jive.impl.JiveOpenClientImpl.java

/**
 * @see org.alfresco.jive.JiveOpenClient#updateDocument(java.lang.String, java.lang.String, java.lang.String, long, java.lang.String)
 *//* w ww  .  j a v  a2  s.c  o m*/
@Override
public void updateDocument(final String userId, final String cmisId, final String fileName, final long fileSize,
        final String mimeType) throws AuthenticationException, CallFailedException, DocumentNotFoundException,
        ServiceUnavailableException, DocumentSizeException {
    final PutMethod put = new PutMethod(buildUrl(OPENCLIENT_API_UPDATE_DOCUMENT));
    final PostMethod temp = new PostMethod();
    int status = -1;

    setCommonHeaders(userId, put);
    put.setRequestHeader("Content-Type", MIME_TYPE_FORM_URLENCODED);

    // These shenanigans are required because PutMethod doesn't directly support content as NameValuePairs.
    temp.setRequestBody(constructNameValuePairs(cmisId, fileName, fileSize, mimeType));
    put.setRequestEntity(temp.getRequestEntity());

    try {
        status = callJive(put);

        if (status >= 400) {
            if (status == 401 || status == 403) {
                throw new AuthenticationException();
            } else if (status == 404) {
                throw new DocumentNotFoundException(cmisId);
            } else if (status == 409) {
                throw new DocumentSizeException(fileName, fileSize);
            } else if (status == 503) {
                throw new ServiceUnavailableException();
            } else {
                throw new CallFailedException(status);
            }
        } else if (status >= 300) {
            log.warn("Status code: " + status + ". cmisObjectID: " + cmisId);
        }
    } catch (final HttpException he) {
        throw new CallFailedException(he);
    } catch (final IOException ioe) {
        throw new CallFailedException(ioe);
    } finally {
        put.releaseConnection();
    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

private String sendPostData(PostMethod post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();
    // Check if we should do a multipart/form-data or an
    // application/x-www-form-urlencoded post request
    if (getUseMultipartForPost()) {
        // If a content encoding is specified, we use that as the
        // encoding of any parameter values
        String contentEncoding = getContentEncoding();
        if (isNullOrEmptyTrimmed(contentEncoding)) {
            contentEncoding = null;//from  w ww. j av  a 2s.com
        }

        final boolean browserCompatible = getDoBrowserCompatibleMultipart();
        // We don't know how many entries will be skipped
        List<PartBase> partlist = new ArrayList<>();
        // Create the parts
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            StringPart part = new StringPart(arg.getName(), arg.getValue(), contentEncoding);
            if (browserCompatible) {
                part.setTransferEncoding(null);
                part.setContentType(null);
            }
            partlist.add(part);
        }

        // Add any files
        for (HTTPFileArg file : files) {
            File inputFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            // We do not know the char set of the file to be uploaded, so we set it to null
            ViewableFilePart filePart = new ViewableFilePart(file.getParamName(), inputFile, file.getMimeType(),
                    null);
            filePart.setCharSet(null); // We do not know what the char set of the file is
            partlist.add(filePart);
        }

        // Set the multipart for the post
        int partNo = partlist.size();
        Part[] parts = partlist.toArray(new Part[partNo]);
        MultipartRequestEntity multiPart = new MultipartRequestEntity(parts, post.getParams());
        post.setRequestEntity(multiPart);

        // Set the content type
        String multiPartContentType = multiPart.getContentType();
        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, multiPartContentType);

        // If the Multipart is repeatable, we can send it first to
        // our own stream, without the actual file content, so we can return it
        if (multiPart.isRepeatable()) {
            // For all the file multiparts, we must tell it to not include
            // the actual file content
            for (int i = 0; i < partNo; i++) {
                if (parts[i] instanceof ViewableFilePart) {
                    ((ViewableFilePart) parts[i]).setHideFileData(true); // .sendMultipartWithoutFileContent(bos);
                }
            }
            // Write the request to our own stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            multiPart.writeRequest(bos);
            bos.flush();
            // We get the posted bytes using the encoding used to create it
            postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient
                    : contentEncoding));
            bos.close();

            // For all the file multiparts, we must revert the hiding of
            // the actual file content
            for (int i = 0; i < partNo; i++) {
                if (parts[i] instanceof ViewableFilePart) {
                    ((ViewableFilePart) parts[i]).setHideFileData(false);
                }
            }
        } else {
            postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
        }
    } else {
        // Check if the header manager had a content type header
        // This allows the user to specify his own content-type for a POST request
        Header contentTypeHeader = post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null
                && contentTypeHeader.getValue().length() > 0;
        // If there are no arguments, we can send a file as the body of the request
        // TODO: needs a multiple file upload scenerio
        if (!hasArguments() && getSendFileAsPostBody()) {
            // If getSendFileAsPostBody returned true, it's sure that file is not null
            HTTPFileArg file = files[0];
            if (!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                if (file.getMimeType() != null && file.getMimeType().length() > 0) {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }

            FileRequestEntity fileRequestEntity = new FileRequestEntity(new File(file.getPath()), null);
            post.setRequestEntity(fileRequestEntity);

            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // In a post request which is not multipart, we only support
            // parameters, no file upload is allowed

            // If a content encoding is specified, we set it as http parameter, so that
            // the post body will be encoded in the specified content encoding
            String contentEncoding = getContentEncoding();
            boolean haveContentEncoding = false;
            if (isNullOrEmptyTrimmed(contentEncoding)) {
                contentEncoding = null;
            } else {
                post.getParams().setContentCharset(contentEncoding);
                haveContentEncoding = true;
            }

            // If none of the arguments have a name specified, we
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // Allow the mimetype of the file to control the content type
                // This is not obvious in GUI if you are not uploading any files,
                // but just sending the content of nameless parameters
                // TODO: needs a multiple file upload scenerio
                if (!hasContentTypeHeader) {
                    HTTPFileArg file = files.length > 0 ? files[0] : null;
                    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else {
                        // TODO - is this the correct default?
                        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                                HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                    }
                }

                // Just append all the parameter values, and use that as the post body
                StringBuilder postBody = new StringBuilder();
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    String value;
                    if (haveContentEncoding) {
                        value = arg.getEncodedValue(contentEncoding);
                    } else {
                        value = arg.getEncodedValue();
                    }
                    postBody.append(value);
                }
                StringRequestEntity requestEntity = new StringRequestEntity(postBody.toString(),
                        post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue(), contentEncoding);
                post.setRequestEntity(requestEntity);
            } else {
                // It is a normal post request, with parameter names and values

                // Set the content type
                if (!hasContentTypeHeader) {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                // Add the parameters
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    // The HTTPClient always urlencodes both name and value,
                    // so if the argument is already encoded, we have to decode
                    // it before adding it to the post request
                    String parameterName = arg.getName();
                    if (arg.isSkippable(parameterName)) {
                        continue;
                    }
                    String parameterValue = arg.getValue();
                    if (!arg.isAlwaysEncoded()) {
                        // The value is already encoded by the user
                        // Must decode the value now, so that when the
                        // httpclient encodes it, we end up with the same value
                        // as the user had entered.
                        String urlContentEncoding = contentEncoding;
                        if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
                            // Use the default encoding for urls
                            urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
                        }
                        parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
                        parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
                    }
                    // Add the parameter, httpclient will urlencode it
                    post.addParameter(parameterName, parameterValue);
                }

                /*
                //                    // Alternative implementation, to make sure that HTTPSampler and HTTPSampler2
                //                    // sends the same post body.
                //
                //                    // Only include the content char set in the content-type header if it is not
                //                    // an APPLICATION_X_WWW_FORM_URLENCODED content type
                //                    String contentCharSet = null;
                //                    if(!post.getRequestHeader(HEADER_CONTENT_TYPE).getValue().equals(APPLICATION_X_WWW_FORM_URLENCODED)) {
                //                        contentCharSet = post.getRequestCharSet();
                //                    }
                //                    StringRequestEntity requestEntity = new StringRequestEntity(getQueryString(contentEncoding), post.getRequestHeader(HEADER_CONTENT_TYPE).getValue(), contentCharSet);
                //                    post.setRequestEntity(requestEntity);
                */
            }

            // If the request entity is repeatable, we can send it first to
            // our own stream, so we can return it
            if (post.getRequestEntity().isRepeatable()) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                post.getRequestEntity().writeRequest(bos);
                bos.flush();
                // We get the posted bytes using the encoding used to create it
                postedBody.append(new String(bos.toByteArray(), post.getRequestCharSet()));
                bos.close();
            } else {
                postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
            }
        }
    }
    // Set the content length
    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH,
            Long.toString(post.getRequestEntity().getContentLength()));

    return postedBody.toString();
}

From source file:org.dasein.persist.riak.RiakCache.java

@Override
public long count(SearchTerm... terms) throws PersistenceException {
    if (terms == null || terms.length < 1) {
        return count();
    }// w w w  .  j  av  a 2 s . com
    if (wire.isDebugEnabled()) {
        startCall("count");
    }
    try {
        String mapFunction = buildMapFunction(true, terms);

        HashMap<String, Object> request = new HashMap<String, Object>();
        HashMap<String, Object> inputs = new HashMap<String, Object>();

        terms = matchKeys(inputs, terms);
        if (inputs.size() < 1) {
            request.put("inputs", getBucket());
        } else {
            inputs.put("bucket", getBucket());
            request.put("inputs", inputs);
        }

        ArrayList<Map<String, Object>> query = new ArrayList<Map<String, Object>>();
        HashMap<String, Object> maps = new HashMap<String, Object>();
        HashMap<String, Object> reduces = new HashMap<String, Object>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        HashMap<String, Object> reduce = new HashMap<String, Object>();

        map.put("language", "javascript");
        map.put("source", mapFunction);
        map.put("keep", true);
        maps.put("map", map);

        reduce.put("language", "javascript");
        reduce.put("keep", true);
        reduce.put("name", "Riak.reduceSum");
        reduces.put("reduce", reduce);

        query.add(maps);
        query.add(reduces);
        request.put("query", query);

        String json = (new JSONObject(request)).toString();

        HttpClient client = getClient();
        PostMethod post = new PostMethod(getEndpoint() + "mapred");
        int code;

        try {
            post.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8"));
            if (wire.isDebugEnabled()) {
                try {
                    wire.debug(post.getName() + " " + getEndpoint() + "mapred");
                    wire.debug("");
                    for (Header h : post.getRequestHeaders()) {
                        wire.debug(h.getName() + ": " + h.getValue());
                    }
                    wire.debug("Content-length: " + post.getRequestEntity().getContentLength());
                    wire.debug("Content-type: " + post.getRequestEntity().getContentType());
                    wire.debug("");
                    wire.debug(((StringRequestEntity) post.getRequestEntity()).getContent());
                    wire.debug("");
                } catch (Throwable ignore) {
                    // ignore
                }
            }
            code = client.executeMethod(post);
        } catch (HttpException e) {
            throw new PersistenceException("HttpException during POST: " + e.getMessage());
        } catch (IOException e) {
            throw new PersistenceException("IOException during POST: " + e.getMessage());
        }
        try {
            String body = post.getResponseBodyAsString();

            try {
                if (wire.isDebugEnabled()) {
                    wire.debug("----------------------------------------");
                    wire.debug("");
                    wire.debug(post.getStatusLine().getStatusCode() + " "
                            + post.getStatusLine().getReasonPhrase());
                    wire.debug("");
                    if (body != null) {
                        wire.debug(body);
                        wire.debug("");
                    }
                }
            } catch (Throwable ignore) {
                // ignore
            }
            if (code != HttpStatus.SC_OK) {
                if (code == HttpStatus.SC_NOT_FOUND) {
                    return 0;
                }
                throw new PersistenceException(code + ": " + body);
            }

            JSONArray results = new JSONArray(body);

            return results.getJSONArray(0).getLong(0);
        } catch (Exception e) {
            throw new PersistenceException(e);
        } catch (Throwable t) {
            throw new PersistenceException(t.getMessage());
        }
    } finally {
        endCall("count");
    }
}

From source file:org.dasein.persist.riak.RiakCache.java

@Override
public T create(Transaction xaction, Map<String, Object> state) throws PersistenceException {
    if (std.isTraceEnabled()) {
        std.trace("ENTER: " + RiakCache.class.getName() + ".create(" + xaction + "," + state + ")");
    }//from w ww.j  a v a  2 s. co  m
    try {
        if (wire.isDebugEnabled()) {
            startCall("create");
        }
        try {
            StringBuilder url = new StringBuilder();
            String key = getPrimaryKeyField();
            Object keyValue = state.get(key);

            url.append(getEndpoint());
            url.append("buckets/");
            url.append(getBucket());
            url.append("/keys/");
            url.append(keyValue);

            HttpClient client = getClient();
            PostMethod post = new PostMethod(url.toString());
            int code;

            try {
                String json = toDataStoreJSONFromCurrentState(state);

                for (Key secondaryKey : getSecondaryKeys()) {
                    if (secondaryKey.getFields().length > 1) {
                        int len = secondaryKey.getFields().length;

                        StringBuilder n = new StringBuilder();
                        StringBuilder v = new StringBuilder();

                        for (int i = 0; i < len; i++) {
                            Object ob = toJSONValue(state.get(secondaryKey.getFields()[i]));

                            if (ob == null) {
                                v.append("=*=");
                            } else {
                                v.append(ob.toString());
                            }
                            n.append(secondaryKey.getFields()[i].toLowerCase());
                            if (i < len - 1) {
                                n.append("-");
                                v.append("\n");
                            }
                        }
                        post.addRequestHeader("x-riak-index-" + n.toString() + "_bin",
                                Base64.encodeBase64String(v.toString().getBytes("utf-8")));
                    }
                    Object ob = toJSONValue(state.get(secondaryKey.getFields()[0]));

                    if (ob != null) {
                        if (ob instanceof Integer || ob instanceof Long) {
                            post.addRequestHeader("x-riak-index-" + secondaryKey.getFields()[0] + "_int",
                                    ob.toString().trim());
                        } else if (ob.getClass().isArray()) {
                            Object[] items = (Object[]) ob;

                            for (Object item : items) {
                                if (item != null) {
                                    boolean binary = true;

                                    if (Number.class.isAssignableFrom(item.getClass())) {
                                        binary = false;
                                    } else if (item.getClass().equals(long.class)
                                            || item.getClass().equals(int.class)
                                            || item.getClass().equals(boolean.class)
                                            || item.getClass().equals(byte.class)) {
                                        binary = false;
                                    }
                                    if (binary) {
                                        try {
                                            String encoded = Base64
                                                    .encodeBase64String(item.toString().getBytes("utf-8"));

                                            post.addRequestHeader("x-riak-index-"
                                                    + secondaryKey.getFields()[0].toLowerCase() + "_bin",
                                                    encoded.trim());
                                        } catch (UnsupportedEncodingException e) {
                                            std.error("No such encoding UTF-8: " + e.getMessage(), e);
                                            throw new PersistenceException(e);
                                        }
                                    } else {
                                        post.addRequestHeader("x-riak-index-"
                                                + secondaryKey.getFields()[0].toLowerCase() + "_int",
                                                item.toString().trim());
                                    }
                                }
                            }
                        } else {
                            try {
                                String encoded = Base64.encodeBase64String(ob.toString().getBytes("utf-8"));

                                post.addRequestHeader(
                                        "x-riak-index-" + secondaryKey.getFields()[0].toLowerCase() + "_bin",
                                        encoded.trim());
                            } catch (UnsupportedEncodingException e) {
                                std.error("No such encoding UTF-8: " + e.getMessage(), e);
                                throw new PersistenceException(e);
                            }
                        }
                        Class<? extends CachedItem> link = secondaryKey.getIdentifies();

                        if (secondaryKey.getFields().length < 2 && link != null) {
                            try {
                                PersistentCache<? extends CachedItem> cache = PersistentCache.getCache(link);

                                if (cache != null && (cache instanceof RiakCache)) {
                                    RiakCache<? extends CachedItem> c = (RiakCache<? extends CachedItem>) cache;
                                    String bucket = c.getBucket();

                                    post.addRequestHeader("Link",
                                            "</buckets/" + bucket + "/keys/" + ob.toString() + ">; riaktag=\""
                                                    + secondaryKey.getFields()[0] + "\"");
                                }
                            } catch (Throwable t) {
                                std.warn("Unable to determine relationship status for "
                                        + secondaryKey.getFields()[0] + ": " + t.getMessage());
                            }
                        }
                    }
                }
                post.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8"));
                if (wire.isDebugEnabled()) {
                    try {
                        wire.debug(post.getName() + " " + url.toString());
                        wire.debug("");
                        for (Header h : post.getRequestHeaders()) {
                            wire.debug(h.getName() + ": " + h.getValue());
                        }
                        wire.debug("Content-length: " + post.getRequestEntity().getContentLength());
                        wire.debug("Content-type: " + post.getRequestEntity().getContentType());
                        wire.debug("");
                        wire.debug(((StringRequestEntity) post.getRequestEntity()).getContent());
                        wire.debug("");
                    } catch (Throwable ignore) {
                        // ignore
                    }
                }
                code = client.executeMethod(post);
            } catch (HttpException e) {
                std.error("HTTP exception during POST: " + e.getMessage());
                throw new PersistenceException("HttpException during POST: " + e.getMessage());
            } catch (IOException e) {
                std.error("I/O exception during POST: " + e.getMessage());
                throw new PersistenceException("I/O exception during POST: " + e.getMessage());
            }
            try {
                String body = post.getResponseBodyAsString();

                try {
                    if (wire.isDebugEnabled()) {
                        wire.debug("----------------------------------------");
                        wire.debug("");
                        wire.debug(post.getStatusLine().getStatusCode() + " "
                                + post.getStatusLine().getReasonPhrase());
                        wire.debug("");
                        if (body != null) {
                            wire.debug(body);
                            wire.debug("");
                        }
                    }
                } catch (Throwable ignore) {
                    // ignore
                }
                if (code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_NOT_FOUND) {
                    std.warn("Failed attempt to create Riak object (" + code + "): " + body);
                    throw new PersistenceException(code + ": " + body);
                }
                return get(keyValue);
            } catch (IOException e) {
                std.error("Error talking to Riak server: " + e.getMessage());
                throw new PersistenceException(e);
            }
        } finally {
            endCall("create");
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("EXIT: " + RiakCache.class.getName() + ".create()");
        }
    }
}

From source file:org.dasein.persist.riak.RiakCache.java

private Iterable<T> execFind(boolean cursor, @Nonnull SearchTerm[] terms,
        @Nullable final JiteratorFilter<T> filter, @Nullable Boolean orderDesc, @Nullable String... orderFields)
        throws PersistenceException {
    if (std.isTraceEnabled()) {
        std.trace("ENTER: " + RiakCache.class.getName() + ".find(" + Arrays.toString(terms) + "," + filter + ","
                + orderDesc + "," + Arrays.toString(orderFields) + ")");
    }// w  w w. ja v a2s  . c om
    try {
        if ((orderFields == null || orderFields.length < 1) && (terms.length == 1
                || (terms.length == 2 && terms[1].getValue() != null && terms[0].getValue() != null
                        && Number.class.isAssignableFrom(terms[0].getValue().getClass())
                        && (terms[1].getValue() instanceof Boolean)))) {
            boolean equals = true;

            for (SearchTerm t : terms) {
                if (!t.getOperator().equals(Operator.EQUALS)) {
                    equals = false;
                    break;
                }
            }
            if (equals) {
                Key key = matchKeys(terms);

                if (key != null) {
                    StringBuilder url = new StringBuilder();
                    String value;

                    url.append(getEndpoint());
                    url.append("buckets/");
                    url.append(getBucket());
                    url.append("/index/");
                    for (int i = 0; i < key.getFields().length; i++) {
                        url.append(key.getFields()[i].toLowerCase());
                        if (i < key.getFields().length - 1) {
                            url.append("-");
                        }
                    }
                    url.append("_");
                    try {
                        if (key.getFields().length > 1) {
                            StringBuilder v = new StringBuilder();

                            url.append("bin");
                            for (int i = 0; i < key.getFields().length; i++) {
                                String f = key.getFields()[i];

                                for (SearchTerm t : terms) {
                                    if (t.getColumn().equalsIgnoreCase(f)) {
                                        Object ob = t.getValue();

                                        if (ob == null) {
                                            ob = "=*=";
                                        }
                                        v.append(ob.toString());
                                        if (i < key.getFields().length - 1) {
                                            v.append("\n");
                                        }
                                        break;
                                    }
                                }
                            }
                            value = Base64.encodeBase64String(v.toString().getBytes("utf-8"));
                        } else if (terms[0].getValue() == null || (!(terms[0].getValue() instanceof Long)
                                && !(terms[0].getValue() instanceof Integer)
                                && !(terms[0].getValue() instanceof Short))) {
                            url.append("bin");
                            value = Base64.encodeBase64String(
                                    (terms[0].getValue() == null ? "" : terms[0].getValue().toString())
                                            .getBytes("utf-8"));
                        } else {
                            url.append("int");
                            value = String.valueOf(((Number) terms[0].getValue()).longValue());
                        }
                    } catch (UnsupportedEncodingException e) {
                        throw new PersistenceException(e);
                    }
                    url.append("/");
                    url.append(value);
                    if (filter == null) {
                        return list(cursor, url.toString(), null);
                    } else {
                        return list(cursor, url.toString(), filter);
                    }
                }
            }
        }
        startCall("findWithMapReduce");
        try {
            HashMap<String, Object> request = new HashMap<String, Object>();
            ArrayList<Map<String, Object>> query = new ArrayList<Map<String, Object>>();
            HashMap<String, Object> maps = new HashMap<String, Object>();
            HashMap<String, Object> map = new HashMap<String, Object>();
            HashMap<String, Object> inputs = new HashMap<String, Object>();

            terms = matchKeys(inputs, terms);
            if (inputs.size() < 1) {
                request.put("inputs", getBucket());
            } else {
                inputs.put("bucket", getBucket());
                request.put("inputs", inputs);
            }
            map.put("language", "javascript");
            map.put("source", buildMapFunction(false, terms));
            map.put("keep", true);
            maps.put("map", map);

            query.add(maps);
            if (orderFields != null && orderFields.length > 0) {
                HashMap<String, Object> reduces = new HashMap<String, Object>();
                HashMap<String, Object> reduce = new HashMap<String, Object>();

                reduce.put("language", "javascript");
                reduce.put("keep", true);
                reduce.put("source", buildReduceSort(orderDesc != null && orderDesc, orderFields));
                reduces.put("reduce", reduce);

                query.add(reduces);
            }
            request.put("query", query);
            String json = (new JSONObject(request)).toString();

            HttpClient client = getClient();
            PostMethod post = new PostMethod(getEndpoint() + "mapred");
            int code;

            try {
                post.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8"));
                if (wire.isDebugEnabled()) {
                    try {
                        wire.debug(post.getName() + " " + getEndpoint() + "mapred");
                        wire.debug("");
                        for (Header h : post.getRequestHeaders()) {
                            wire.debug(h.getName() + ": " + h.getValue());
                        }
                        wire.debug("Content-length: " + post.getRequestEntity().getContentLength());
                        wire.debug("Content-type: " + post.getRequestEntity().getContentType());
                        wire.debug("");
                        wire.debug(((StringRequestEntity) post.getRequestEntity()).getContent());
                        wire.debug("");
                    } catch (Throwable ignore) {
                        // ignore
                    }
                }
                code = client.executeMethod(post);
            } catch (HttpException e) {
                throw new PersistenceException("HttpException during POST: " + e.getMessage());
            } catch (IOException e) {
                throw new PersistenceException("IOException during POST: " + e.getMessage());
            }
            try {
                String body = post.getResponseBodyAsString();

                try {
                    if (wire.isDebugEnabled()) {
                        wire.debug("----------------------------------------");
                        wire.debug("");
                        wire.debug(post.getStatusLine().getStatusCode() + " "
                                + post.getStatusLine().getReasonPhrase());
                        wire.debug("");
                        if (body != null) {
                            wire.debug(body);
                            wire.debug("");
                        }
                    }
                } catch (Throwable ignore) {
                    // ignore
                }
                if (code != HttpStatus.SC_OK) {
                    if (code == HttpStatus.SC_NOT_FOUND) {
                        return Collections.emptyList();
                    }
                    throw new PersistenceException(code + ": " + body);
                }
                final JSONArray results = ((orderFields != null && orderFields.length > 0)
                        ? (new JSONArray(body)).getJSONArray(0)
                        : new JSONArray(body));
                final int len = results.length();

                if (cursor) {
                    CursorPopulator<T> populator = new CursorPopulator<T>(getTarget().getName() + ".find",
                            null) {
                        @Override
                        public void populate(ForwardCursor<T> cursor) {
                            try {
                                for (int i = 0; i < len; i++) {
                                    JSONObject ob = results.getJSONObject(i);

                                    if (std.isDebugEnabled()) {
                                        std.debug("find - checking cache for " + ob.get(getPrimaryKeyField()));
                                    }
                                    T item = getCache().find(getPrimaryKeyField(),
                                            ob.get(getPrimaryKeyField()));

                                    if (item == null) {
                                        if (std.isDebugEnabled()) {
                                            std.debug("find - cache miss, loading "
                                                    + ob.get(getPrimaryKeyField()));
                                        }
                                        String version = "0";

                                        if (ob.has("SCHEMA_VERSION")) {
                                            version = ob.getString("SCHEMA_VERSION");
                                        }
                                        item = toTargetFromJSON(version, ob);
                                        if (item != null) {
                                            getCache().cache(item);
                                        }
                                    }
                                    if (item != null) {
                                        try {
                                            if (filter == null || filter.filter(item)) {
                                                cursor.push(item);
                                            }
                                        } catch (Throwable t) {
                                            throw new RuntimeException(t);
                                        }
                                    }
                                }
                            } catch (Throwable t) {
                                throw new JiteratorLoadException(t);
                            }
                        }
                    };

                    populator.populate();
                    if (filter == null) {
                        populator.setSize(len);
                    }
                    return populator.getCursor();
                } else {
                    PopulatorThread<T> populator = new PopulatorThread<T>(new JiteratorPopulator<T>() {
                        @Override
                        public void populate(@Nonnull Jiterator<T> iterator) throws Exception {
                            for (int i = 0; i < len; i++) {
                                JSONObject ob = results.getJSONObject(i);

                                if (std.isDebugEnabled()) {
                                    std.debug("find - checking cache for " + ob.get(getPrimaryKeyField()));
                                }
                                T item = getCache().find(getPrimaryKeyField(), ob.get(getPrimaryKeyField()));

                                if (item == null) {
                                    if (std.isDebugEnabled()) {
                                        std.debug("find - cache miss, loading " + ob.get(getPrimaryKeyField()));
                                    }
                                    String version = "0";

                                    if (ob.has("SCHEMA_VERSION")) {
                                        version = ob.getString("SCHEMA_VERSION");
                                    }
                                    item = toTargetFromJSON(version, ob);
                                    if (item != null) {
                                        getCache().cache(item);
                                    }
                                }
                                if (item != null) {
                                    try {
                                        if (filter == null || filter.filter(item)) {
                                            iterator.push(item);
                                        }
                                    } catch (Throwable t) {
                                        throw new RuntimeException(t);
                                    }
                                }
                            }
                        }
                    });
                    populator.populate();
                    if (filter == null) {
                        populator.setSize(len);
                    }
                    return populator.getResult();
                }
            } catch (Exception e) {
                std.error(e.getMessage(), e);
                throw new PersistenceException(e);
            }
        } finally {
            endCall("findWithMapReduce");
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("EXIT: " + RiakCache.class.getName() + ".find()");
        }
    }
}

From source file:org.geoserver.gss.HTTPGSSClient.java

/**
 * Executes the http method, checks the response status, parses the response and returns it.
 * Will throw an exception in case of communication errors, error codes, or service exceptions
 * //from   ww  w . j a v a2  s . co  m
 * @throws IOException
 */
Object executeMethod(HttpMethod method) throws IOException {
    Object response;
    try {
        if (LOGGER.isLoggable(Level.FINE)) {
            if (method instanceof GetMethod) {
                GetMethod gm = (GetMethod) method;
                LOGGER.fine("Sending GET request:\n " + method.getURI());
            } else if (method instanceof PostMethod) {
                PostMethod pm = (PostMethod) method;
                XMLEntity entity = (XMLEntity) pm.getRequestEntity();
                String request = entity.toString();
                LOGGER.fine("Sending POST request:\n " + method.getURI() + "\n" + request);
                // ugly, but Encoder cannot be reused, so we have to set a new entity
                // that uses the already generated string
                pm.setRequestEntity(new StringRequestEntity(request, "text/xml", "UTF-8"));
            } else {
                LOGGER.fine("Sending unknown method type : " + method);
            }
        }

        // plain execution
        int statusCode = client.executeMethod(method);

        // check the HTTP status
        if (statusCode != HttpStatus.SC_OK) {
            throw new IOException("HTTP client returned with code " + statusCode);
        }

        // parse the response
        Parser parser = new Parser(configuration);
        parser.setStrict(true);
        parser.setFailOnValidationError(true);
        InputStream is;
        if (LOGGER.isLoggable(Level.FINE)) {
            String responseString = method.getResponseBodyAsString();
            LOGGER.log(Level.FINE, "Response from Unit:\n" + responseString);
            is = new ByteArrayInputStream(responseString.getBytes());
        } else {
            is = method.getResponseBodyAsStream();
        }
        response = parser.parse(is);
    } catch (Exception e) {
        throw (IOException) new IOException("Error occurred while executing " + "a call to the Unit")
                .initCause(e);
    } finally {
        method.releaseConnection();
    }

    // convert a service exception into an IOException if necessary
    if (response instanceof ExceptionReportType) {
        ExceptionReportType report = (ExceptionReportType) response;
        StringBuilder sb = new StringBuilder("The Unit service reported a failure: ");
        for (Iterator it = report.getException().iterator(); it.hasNext();) {
            ExceptionType et = (ExceptionType) it.next();
            for (Iterator eit = et.getExceptionText().iterator(); eit.hasNext();) {
                String text = (String) eit.next();
                sb.append(text);
                if (eit.hasNext())
                    sb.append(". ");
            }

        }

        throw new IOException(sb.toString());
    }

    return response;
}

From source file:org.infoscoop.request.PostCredentialAuthenticator.java

public void doAuthentication(HttpClient client, ProxyRequest request, HttpMethod method, String uid, String pwd)
        throws ProxyAuthenticationException {
    String uidParamNameHeader = request.getRequestHeader(UID_PARAM_NAME);
    String passwdParamNameHeader = request.getRequestHeader(PASSWD_PARAM_NAME);
    String uidParamName = (uidParamNameHeader != null) ? uidParamNameHeader : this.uidParamName;
    String passwdParamName = (passwdParamNameHeader != null) ? passwdParamNameHeader : this.pwdParamName;
    try {/*from www .  j a  v  a 2 s  .  com*/
        request.addIgnoreHeader("Content-Type");

        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
        NameValuePair[] params = new NameValuePair[2];

        PostMethod pMethod = (PostMethod) method;
        String queryString = pMethod.getQueryString();

        // Delete the same parameter's name that has already exist.
        pMethod.removeParameter(uidParamName);
        pMethod.removeParameter(passwdParamName);
        queryString = RequestUtil.removeQueryStringParam(queryString, uidParamName);
        queryString = RequestUtil.removeQueryStringParam(queryString, passwdParamName);

        pMethod.setQueryString(queryString);

        params[0] = new NameValuePair(uidParamName, uid);
        params[1] = new NameValuePair(passwdParamName, pwd);
        pMethod.setRequestBody(params);

        pMethod.addRequestHeader("content-length",
                String.valueOf(pMethod.getRequestEntity().getContentLength()));
    } catch (Exception e) {
        throw new ProxyAuthenticationException(e);
    }
}

From source file:org.zend.usagedata.internal.recording.uploading.BasicUploader.java

/**
 * This method does the heavy lifting when it comes to downloads.
 * //from  www . j a  v  a2s.  c  o m
 * I can envision a time when we may want to upload something other than files.
 * We may, for example, want to upload an in-memory representation of the files.
 * For now, in the spirit of having something that works is better than
 * overengineering something you may not need, we're just dealing with files.
 * 
 * @param monitor
 *            an instance of something that implements
 *            {@link IProgressMonitor}. Must not be <code>null</code>.
 * @throws Exception 
 */
UploadResult doUpload(IProgressMonitor monitor) throws Exception {
    monitor.beginTask("Upload", getUploadParameters().getFiles().length + 3); //$NON-NLS-1$
    /*
     * The files that we have been provided with were determined while the recorder
     * was suspended. We should be safe to work with these files without worrying
     * that other threads are messing with them. We do need to consider that other
     * processes running outside of our JVM may be messing with these files and
     * anticipate errors accordingly.
     */

    // TODO Does it make sense to create a custom exception for this?
    if (!hasUserAuthorizedUpload())
        throw new Exception("User has not authorized upload."); //$NON-NLS-1$

    /*
     * There appears to be some mechanism on some versions of HttpClient that
     * allows the insertion of compression technology. For now, we don't worry
     * about compressing our output; we can worry about that later.
     */
    PostMethod post = new PostMethod(getSettings().getUploadUrl());

    post.setRequestHeader(HTTP_USERID, getSettings().getUserId());
    post.setRequestHeader(HTTP_WORKSPACEID, getSettings().getWorkspaceId());
    post.setRequestHeader(HTTP_TIME, String.valueOf(System.currentTimeMillis()));
    post.setRequestHeader(USER_AGENT, getSettings().getUserAgent());

    boolean loggingServerActivity = getSettings().isLoggingServerActivity();
    if (loggingServerActivity) {
        post.setRequestHeader("LOGGING", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    post.setRequestEntity(new MultipartRequestEntity(getFileParts(monitor), post.getParams()));
    post.setRequestHeader(CONTENT_LENGTH, String.valueOf(post.getRequestEntity().getContentLength()));
    // Configure the HttpClient to timeout after one minute.
    HttpClientParams httpParameters = new HttpClientParams();
    httpParameters.setSoTimeout(getSocketTimeout()); // "So" means "socket"; who knew?

    monitor.worked(1);

    int result = new HttpClient(httpParameters).executeMethod(post);

    handleServerResponse(post);

    monitor.worked(1);

    post.releaseConnection();

    // Check the result. HTTP return code of 200 means success.
    if (result == 200) {
        for (File file : getUploadParameters().getFiles()) {
            // TODO what if file delete fails?
            if (file.exists())
                file.delete();
        }
    }

    monitor.worked(1);

    monitor.done();

    return new UploadResult(result);
}