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

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

Introduction

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

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:com.zimbra.cs.fb.ExchangeFreeBusyProvider.java

private boolean formAuth(HttpClient client, ServerInfo info) throws IOException {
    StringBuilder buf = new StringBuilder();
    buf.append("destination=");
    buf.append(URLEncoder.encode(info.url, "UTF-8"));
    buf.append("&username=");
    buf.append(info.authUsername);// w w w .  j  ava 2 s  .  co  m
    buf.append("&password=");
    buf.append(URLEncoder.encode(info.authPassword, "UTF-8"));
    buf.append("&flags=0");
    buf.append("&SubmitCreds=Log On");
    buf.append("&trusted=0");
    String url = info.url + LC.calendar_exchange_form_auth_url.value();
    PostMethod method = new PostMethod(url);
    ByteArrayRequestEntity re = new ByteArrayRequestEntity(buf.toString().getBytes(), "x-www-form-urlencoded");
    method.setRequestEntity(re);
    HttpState state = new HttpState();
    client.setState(state);
    try {
        int status = HttpClientUtil.executeMethod(client, method);
        if (status >= 400) {
            ZimbraLog.fb.error("form auth to Exchange returned an error: " + status);
            return false;
        }
    } finally {
        method.releaseConnection();
    }
    return true;
}

From source file:com.funambol.json.dao.JsonDAOImpl.java

public JsonResponse beginSync(String token, String jsonObject) throws HttpException, IOException {

    String request = Utility.getUrl(jsonServerUrl, resourceType, BEGIN_SYNC_URL);

    if (log.isTraceEnabled()) {
        log.trace("Starting sync..");
    }//w  w w.j  ava2 s .c  o m

    PostMethod post = new PostMethod(request);
    post.setRequestHeader(Utility.TOKEN_HEADER_NAME, token);
    post.setRequestEntity(new StringRequestEntity(jsonObject));

    if (log.isTraceEnabled()) {
        log.trace(
                "Request received [" + request + "] for token [" + token + "] and json [" + jsonObject + "]..");
    }

    int statusCode = 0;
    String responseBody = null;
    try {
        statusCode = httpClient.executeMethod(post);
        responseBody = post.getResponseBodyAsString();
    } finally {
        post.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("Response after starting sync [" + responseBody + "]");
    }

    JsonResponse response = new JsonResponse(statusCode, responseBody);

    return response;
}

From source file:com.funambol.json.dao.JsonDAOImpl.java

public JsonResponse getItemKeysFromTwin(String token, String jsonContent) throws HttpException, IOException {

    String request = Utility.getUrl(jsonServerUrl, resourceType, GET_ITEM_FROM_TWIN_URL);

    PostMethod post = new PostMethod(request);
    post.setRequestHeader(Utility.TOKEN_HEADER_NAME, token);
    post.setRequestEntity(new StringRequestEntity(jsonContent));

    if (log.isTraceEnabled()) {
        log.trace("Getting item keys from twin..");
    }//w ww.ja va2 s.c  o m

    if (Configuration.getConfiguration().isDebugMode()) {
        if (log.isTraceEnabled()) {
            log.trace("Getting item keys from twin of '" + jsonContent + "'");
        }
    }

    int statusCode = 0;
    String responseBody = null;
    try {
        statusCode = httpClient.executeMethod(post);
        responseBody = post.getResponseBodyAsString();
    } finally {
        post.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("Found item keys from twin '" + responseBody + "'");
    }

    JsonResponse response = new JsonResponse(statusCode, responseBody);

    return response;
}

From source file:au.edu.usq.fascinator.harvester.fedora.restclient.FedoraRestClient.java

public void ingest(String pid, Properties options, File content) throws IOException {
    StringBuilder uri = new StringBuilder(getBaseUrl());
    uri.append("/objects/");
    uri.append(pid);/*from   ww  w .  ja  v a 2 s . co m*/
    addParam(uri, options, "label");
    addParam(uri, options, "format");
    addParam(uri, options, "encoding");
    addParam(uri, options, "namespace");
    addParam(uri, options, "ownerId");
    addParam(uri, options, "logMessage");
    PostMethod method = new PostMethod(uri.toString());
    RequestEntity request = null;
    if (content == null) {
        request = new StringRequestEntity("", "text/xml", "UTF-8");
    } else {
        String mimeType = options.getProperty("mimeType", getMimeType(content));
        request = new FileRequestEntity(content, mimeType);
    }
    method.setRequestEntity(request);
    executeMethod(method);
    method.releaseConnection();
}

From source file:de.mpg.escidoc.http.UserGroup.java

@SuppressWarnings("deprecation")
public Boolean removeSelectorFromUserGroup() {
    String userGroupID = Util.input("Enter UserGroupID whose Selectors you want to edit:");
    String selectors = Util.input("Enter SelectorID(s) to remove from the UserGroup (separated by \",\"): ");
    // String userGroupID = "escidoc:27004";
    // String selectors = "escidoc:27014,escidoc:27013";
    Document userGroupXML = this.getUserGroupXML(userGroupID);
    if (userGroupXML == null) {
        return false;
    }/*from  w  w  w.  jav a  2s.co  m*/
    Element rootElement = userGroupXML.getRootElement();
    String lastModificationDate = rootElement.getAttributeValue("last-modification-date");
    if (this.USER_HANDLE != null) {
        Document responseXML = null;
        PostMethod post = new PostMethod(
                this.FRAMEWORK_URL + "/aa/user-group/" + userGroupID + "/selectors/remove");
        post.setRequestHeader("Cookie", "escidocCookie=" + this.USER_HANDLE);
        try {
            System.out.println("Request body sent to Server: ");
            post.setRequestEntity(new StringRequestEntity(
                    Util.getParamXml(Util.OPTION_REMOVE_SELECTOR, lastModificationDate, selectors)));
            this.client.executeMethod(post);
            if (post.getStatusCode() != 200) {
                System.out.println("Server StatusCode: " + post.getStatusCode());
                return false;
            }
            System.out.println("Server response: ");
            responseXML = Util.inputStreamToXmlDocument(post.getResponseBodyAsStream());
            Util.xmlToString(responseXML);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("Error in removeSelectorFromUserGroup: No userHandle available");
    }
    return true;
}

From source file:com.kylinolap.jdbc.stub.KylinClient.java

@Override
public void connect() throws ConnectionException {
    PostMethod post = new PostMethod(conn.getConnectUrl());
    HttpClient httpClient = new HttpClient();

    if (conn.getConnectUrl().toLowerCase().startsWith("https://")) {
        registerSsl();/*from  w  w w  . j  av  a  2s.co  m*/
    }
    addPostHeaders(post);

    try {
        StringRequestEntity requestEntity = new StringRequestEntity("{}", "application/json", "UTF-8");
        post.setRequestEntity(requestEntity);
        httpClient.executeMethod(post);

        if (post.getStatusCode() != 200 && post.getStatusCode() != 201) {
            logger.error("Authentication Failed with error code " + post.getStatusCode() + " and message:\n"
                    + post.getResponseBodyAsString());

            throw new ConnectionException("Authentication Failed.");
        }
    } catch (HttpException e) {
        logger.error(e.getLocalizedMessage(), e);
        throw new ConnectionException(e.getLocalizedMessage());
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage(), e);
        throw new ConnectionException(e.getLocalizedMessage());
    }
}

From source file:de.mpg.escidoc.http.UserGroup.java

@SuppressWarnings("deprecation")
public Boolean addSelectorToUserGroup() {
    String userGroupID = Util.input("Enter UserGroupID whose Selectors you want to edit:");
    String selectorType = Util.input(
            "Which kind of Selectors do you want to add (\"user-account\" / \"user-group\" / \"organizational-unit\"): ");
    String selectors = Util.input("Enter the UserID(s) you want to add as Selectors (separated by \",\"): ");
    // String userGroupID = "escidoc:27004";
    // String selectors = "escidoc:exuser1,escidoc:3029";
    Document userGroupXML = this.getUserGroupXML(userGroupID);
    if (userGroupXML == null) {
        return false;
    }/*from   www  . j  a  v a2 s  . co  m*/
    Element rootElement = userGroupXML.getRootElement();
    String lastModificationDate = rootElement.getAttributeValue("last-modification-date");
    if (this.USER_HANDLE != null) {
        Document responseXML = null;
        PostMethod post = new PostMethod(
                this.FRAMEWORK_URL + "/aa/user-group/" + userGroupID + "/selectors/add");
        post.setRequestHeader("Cookie", "escidocCookie=" + this.USER_HANDLE);
        try {
            System.out.println("Request body sent to Server: ");
            post.setRequestEntity(new StringRequestEntity(Util.getParamXml(Util.OPTION_ADD_SELECTOR,
                    lastModificationDate, selectors,
                    (selectorType.equalsIgnoreCase("organizational-unit") ? "o" : selectorType),
                    selectorType.equalsIgnoreCase("organizational-unit") ? "user-attribute" : "internal")));
            this.client.executeMethod(post);
            if (post.getStatusCode() != 200) {
                System.out.println("Server StatusCode: " + post.getStatusCode());
                return false;
            }
            System.out.println("Server response: ");
            responseXML = Util.inputStreamToXmlDocument(post.getResponseBodyAsStream());
            Util.xmlToString(responseXML);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("Error in addSelectorToUserGroup: No userHandle available");
    }
    return true;
}

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  ww  w  .j  a v a  2 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.cs.fb.ExchangeMessage.java

public HttpMethod createMethod(String uri, FreeBusy fb) throws IOException {
    // PROPPATCH/*from   w  ww  .j  av  a 2  s . c o m*/
    PostMethod method = new PostMethod(uri) {
        private String PROPPATCH = "PROPPATCH";

        public String getName() {
            return PROPPATCH;
        }
    };
    Document doc = createRequest(fb);
    byte[] buf = DomUtil.getBytes(doc);
    if (ZimbraLog.fb.isDebugEnabled())
        ZimbraLog.fb.debug(new String(buf, "UTF-8"));
    ByteArrayRequestEntity re = new ByteArrayRequestEntity(buf, "text/xml");
    method.setRequestEntity(re);
    return method;
}

From source file:com.funambol.json.dao.JsonDAOImpl.java

public JsonResponse addItem(String token, String jsonObject, long since) throws HttpException, IOException {

    String request = Utility.getUrl(jsonServerUrl, resourceType, ADD_ITEM_URL);

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: start addItem; since=" + since);
    }/*from w w  w. j a v  a2s .co m*/

    PostMethod post = new PostMethod(request);
    post.setRequestHeader(Utility.TOKEN_HEADER_NAME, token);
    post.setRequestEntity(new StringRequestEntity(jsonObject));

    if (since != 0) {
        NameValuePair nvp_since = new NameValuePair();
        nvp_since.setName("since");
        nvp_since.setValue("" + since);
        NameValuePair[] nvp = { nvp_since };
        post.setQueryString(nvp);
    }

    if (log.isTraceEnabled()) {
        log.trace("addItem Request: " + request);
    }
    if (Configuration.getConfiguration().isDebugMode()) {
        if (log.isTraceEnabled()) {
            log.trace("JSON to add " + jsonObject);
        }
    }

    int statusCode = 0;
    String responseBody = null;

    try {
        statusCode = httpClient.executeMethod(post);
        responseBody = post.getResponseBodyAsString();
    } finally {
        post.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("JsonDAOImpl: statusCode " + statusCode + "; added item" + responseBody);
        log.trace("JsonDAOImpl: item added");
    }

    JsonResponse response = new JsonResponse(statusCode, responseBody);

    return response;
}