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

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

Introduction

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

Prototype

public StringRequestEntity(String paramString1, String paramString2, String paramString3)
  throws UnsupportedEncodingException

Source Link

Usage

From source file:com.inbravo.scribe.rest.service.crm.zd.ZDV2RESTCRMService.java

@Override
public final ScribeCommandObject createObject(final ScribeCommandObject cADCommandObject) throws Exception {
    logger.debug("----Inside createObject");
    PostMethod postMethod = null;/*from  w ww . j  av a 2 s .  co  m*/
    try {

        String serviceURL = null;
        String serviceProtocol = null;
        String userId = null;
        String password = null;
        String sessionId = null;
        String crmPort = "80";

        /* Get agent from session manager */
        final ScribeCacheObject cacheObject = zDCRMSessionManager
                .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

        /* Get CRM information from agent */
        serviceURL = cacheObject.getScribeMetaObject().getCrmServiceURL();
        serviceProtocol = cacheObject.getScribeMetaObject().getCrmServiceProtocol();
        userId = cacheObject.getScribeMetaObject().getCrmUserId();
        password = cacheObject.getScribeMetaObject().getCrmPassword();
        crmPort = cacheObject.getScribeMetaObject().getCrmPort();

        /* Create Zen desk URL */
        final String zenDeskURL = serviceProtocol + "://" + serviceURL + zdAPISubPath
                + cADCommandObject.getObjectType().toLowerCase() + "s.json";

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside createObject zenDeskURL: " + zenDeskURL);
        }

        /* Instantiate get method */
        postMethod = new PostMethod(zenDeskURL);

        /* Set request content type */
        postMethod.addRequestHeader("Content-Type", "application/json");
        postMethod.addRequestHeader("accept", "application/json");

        /* Cookie is required to be set for session management */
        postMethod.addRequestHeader("Cookie", sessionId);

        /* Add request entity */
        final RequestEntity entity = new StringRequestEntity(
                ZDCRMMessageFormatUtils.getCreateRequestJSON(cADCommandObject), null, null);
        postMethod.setRequestEntity(entity);

        final HttpClient httpclient = new HttpClient();

        /* Set credentials */
        httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)),
                new UsernamePasswordCredentials(userId, password));

        /* Execute method */
        int result = httpclient.executeMethod(postMethod);

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside createObject response code: " + result + " & body: "
                    + postMethod.getResponseBodyAsString());
        }

        /* Check if object is created */
        if (result == HttpStatus.SC_OK || result == HttpStatus.SC_CREATED) {

            /* Create Scribe object from JSON response */
            return this.createCreateResponse(postMethod.getResponseBodyAsString(),
                    cADCommandObject.getObjectType().toLowerCase());

        } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED
                || result == HttpStatus.SC_NOT_ACCEPTABLE || result == HttpStatus.SC_UNPROCESSABLE_ENTITY) {

            /* Throw user error with valid reasons */
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : "
                    + ZDCRMMessageFormatUtils.getErrorFromResponse(postMethod.getResponseBodyAsString()));
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {

            /* Throw user error with valid reasons */
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {

            /* Throw user error with valid reasons */
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM");
        } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {

            /* Throw user error with valid reasons */
            throw new ScribeException(ScribeResponseCodes._1004
                    + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct");
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final JSONException e) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                e);
    } catch (final ParserConfigurationException exception) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                exception);
    } catch (final SAXException exception) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                exception);
    } catch (final IOException exception) {

        /* Throw user error */
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } finally {
        /* Release connection socket */
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}

From source file:com.salesmanager.core.module.impl.integration.payment.AuthorizeNetTransactionImpl.java

public GatewayTransactionVO captureTransaction(IntegrationKeys ik, IntegrationProperties props,
        MerchantStore store, Order order, GatewayTransactionVO trx, Customer customer, CoreModuleService cis)
        throws TransactionException {

    PostMethod httppost = null;/*from w  ww. j a  v  a  2 s  .  c  o m*/
    try {

        if (cis == null) {
            // throw new
            // Exception("Central integration services not configured for "
            // + PaymentConstants.PAYMENT_LINKPOINTNAME + " and country id "
            // + origincountryid);
            log.error("Central integration services not configured for "
                    + PaymentConstants.PAYMENT_AUTHORIZENETNAME + " and country id " + store.getCountry());
            TransactionException te = new TransactionException(
                    "Central integration services not configured for "
                            + PaymentConstants.PAYMENT_AUTHORIZENETNAME + " and country id "
                            + store.getCountry());
            te.setErrorcode("01");
            throw te;
        }

        String host = cis.getCoreModuleServiceProdDomain();
        String protocol = cis.getCoreModuleServiceProdProtocol();
        String port = cis.getCoreModuleServiceProdPort();
        String url = cis.getCoreModuleServiceProdEnv();
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            host = cis.getCoreModuleServiceDevDomain();
            protocol = cis.getCoreModuleServiceDevProtocol();
            port = cis.getCoreModuleServiceDevPort();
            url = cis.getCoreModuleServiceDevEnv();
        }

        // parse sent elements required
        AuthorizeNetParsedElements pe = null;
        pe = new AuthorizeNetParsedElements();
        Digester digester = new Digester();
        digester.push(pe);

        digester.addCallMethod("transaction/x_card_num", "setCardnumber", 0);
        digester.addCallMethod("transaction/approvalcode", "setApprovalCode", 0);
        digester.addCallMethod("transaction/x_exp_date", "setExpiration", 0);
        digester.addCallMethod("transaction/x_amount", "setTransactionAmount", 0);
        digester.addCallMethod("transaction/x_card_code", "setCvv", 0);

        Reader reader = new StringReader(trx.getTransactionDetails().getGatewaySentDecrypted().trim());

        digester.parse(reader);

        // sb builds the nv pair to authorize net
        StringBuffer sb = new StringBuffer();

        // mandatory name/value pairs for all AIM CC transactions
        // as well as some "good to have" values
        sb.append("x_login=").append(ik.getUserid()).append("&"); // replace
        // with
        // your
        // own
        sb.append("x_tran_key=").append(ik.getTransactionKey()).append("&"); // replace
        // with
        // your
        // own
        sb.append("x_version=3.1&");// set to required in the specs

        // if dev
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            sb.append("x_test_request=TRUE&"); // for testing
        }

        sb.append("x_method=CC&");// required, CC or ECHECK
        sb.append("x_type=CAPTURE_ONLY&");

        // need ccard number
        sb.append("x_card_num=").append(pe.getCardnumber()).append("&");// at
        // least
        // 4
        // last
        // card
        // digit
        sb.append("x_exp_date=").append(pe.getExpiration()).append("&");
        sb.append("x_amount=").append(pe.getTransactionAmount()).append("&");
        if (pe.getCvv() != null) {
            sb.append("x_card_code=").append(pe.getCvv()).append("&");
        }

        sb.append("x_delim_data=TRUE&");
        sb.append("x_delim_char=|&");
        sb.append("x_relay_response=FALSE&");
        sb.append("x_auth_code=").append(trx.getInternalGatewayOrderId()).append("&");

        /** debug **/
        StringBuffer sblog = new StringBuffer();
        sblog.append("x_login=").append(ik.getUserid()).append("&"); // replace
        // with
        // your
        // own
        sblog.append("x_tran_key=").append(ik.getTransactionKey()).append("&"); // replace                                                // own
        sblog.append("x_version=3.1&");// set to required in the specs
        // if dev
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            sblog.append("x_test_request=TRUE&"); // for testing
        }
        sblog.append("x_method=CC&");// required, CC or ECHECK
        sblog.append("x_type=CAPTURE_ONLY&");
        // need ccard number
        sblog.append("x_card_num=").append(CreditCardUtil.maskCardNumber(pe.getCardnumber())).append("&");// at
        // least
        // 4
        // last
        // card
        // digit
        sblog.append("x_exp_date=").append(pe.getExpiration()).append("&");
        sblog.append("x_amount=").append(pe.getTransactionAmount()).append("&");
        if (pe.getCvv() != null) {
            sblog.append("x_card_code=").append(pe.getCvv()).append("&");
        }
        sblog.append("x_delim_data=TRUE&");
        sblog.append("x_delim_char=|&");
        sblog.append("x_relay_response=FALSE&");
        sblog.append("x_auth_code=").append(trx.getInternalGatewayOrderId()).append("&");

        log.debug(sblog.toString());
        /** log **/

        // sx builds the xml for persisting local
        StringBuffer sx = new StringBuffer();

        sx.append("<transaction>");
        sx.append("<x_login>").append(ik.getUserid()).append("</x_login>"); // replace
        // with
        // your
        // own
        sx.append("<x_tran_key>").append(ik.getTransactionKey()).append("</x_tran_key>"); // replace with your own
        sx.append("<x_version>3.1</x_version>");// set to required in the
        // specs

        // if dev
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            sx.append("<x_test_request>TRUE</x_test_request>"); // for
            // testing
        }

        sx.append("<x_method>CC</x_method>");// required, CC or ECHECK
        sx.append("<x_type>CAPTURE_ONLY</x_type>");

        // need ccard number
        sx.append("<x_card_num>").append(pe.getCardnumber()).append("</x_card_num>");// at least 4 last card digit
        sx.append("<x_exp_date>").append(pe.getExpiration()).append("</x_exp_date>");
        sx.append("<x_amount>").append(pe.getTransactionAmount()).append("</x_amount>");
        if (pe.getCvv() != null) {
            sx.append("<x_card_code>").append(pe.getCvv()).append("</x_card_code>");
        }

        sx.append("<x_delim_data>TRUE</x_delim_data>");
        sx.append("<x_delim_char>|</x_delim_char>");
        sx.append("<x_relay_response>FALSE</x_relay_response>");
        sx.append("<x_auth_code>").append(trx.getInternalGatewayOrderId()).append("</x_auth_code>");
        sx.append("</transaction>");

        // x_encap_char
        // use cvv x_card_code
        // x_amount
        // x_recurring_billing NO
        // x_customer_ip

        HttpClient client = new HttpClient();

        httppost = new PostMethod(protocol + "://" + host + ":" + port + url);
        RequestEntity entity = new StringRequestEntity(sb.toString(), "text/plain", "UTF-8");
        httppost.setRequestEntity(entity);

        // open secure connection
        // URL anurl = new URL(protocol + "://" + host + ":" + port + url);

        /*
         * NOTE: If you want to use SSL-specific features,change to:
         * HttpsURLConnection connection = (HttpsURLConnection)
         * url.openConnection();
         */

        String stringresult = null;

        int result = client.executeMethod(httppost);
        if (result != 200) {
            log.error("Communication Error with Authorizenet " + protocol + "://" + host + ":" + port + url);

            throw new Exception(
                    "Communication Error with Authorizenet " + protocol + "://" + host + ":" + port + url);
        }

        // stringresult = httppost.getResponseBodyAsString();
        // log.debug("AuthorizeNet response " +stringresult);

        stringresult = httppost.getResponseBodyAsString();
        log.debug("AuthorizeNet response " + stringresult);

        StringBuffer appendresult = new StringBuffer().append(order.getTotal()).append("|")
                .append(stringresult);

        // Format to xml
        //
        String finalresult = this.readresponse("|", appendresult.toString());

        pe = new AuthorizeNetParsedElements();
        digester = new Digester();
        digester.push(pe);

        digester.addCallMethod("transaction/transactionid", "setTransactionId", 0);
        digester.addCallMethod("transaction/approvalcode", "setApprovalCode", 0);
        digester.addCallMethod("transaction/responsecode", "setResponseCode", 0);
        digester.addCallMethod("transaction/amount", "setTransactionAmount", 0);
        digester.addCallMethod("transaction/reasontext", "setReasontext", 0);
        digester.addCallMethod("transaction/reasoncode", "setReasonCode", 0);

        reader = new StringReader(finalresult);

        digester.parse(reader);

        pe.setTransactionId(trx.getTransactionDetails().getMerchantPaymentGwOrderid());// BECAUSE NOT RETURNED FROM
        // AUTHORIZE NET !!!!

        return this.parseResponse(PaymentConstants.CAPTURE, sx.toString(), finalresult, pe, order,
                order.getTotal());

    } catch (Exception e) {
        if (e instanceof TransactionException) {
            throw (TransactionException) e;
        }
        log.error(e);

        TransactionException te = new TransactionException("AuthorizeNet Gateway error ", e);
        throw te;
    } finally {
        if (httppost != null) {
            httppost.releaseConnection();
        }
    }

}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public void updateCurrency(Currency currency) {
    String resource = String.format(baseUrl + CURRENCIES, currency.getCode());
    PutMethod method = new PutMethod(resource);
    try {// www. j a  va 2  s  . c o  m
        String data = serialize(currency);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.intellij.lang.jsgraphql.ide.project.JSGraphQLLanguageUIProjectService.java

public void executeGraphQL(Editor editor, VirtualFile virtualFile) {
    final JSGraphQLEndpointsModel endpointsModel = editor.getUserData(JS_GRAPH_QL_ENDPOINTS_MODEL);
    if (endpointsModel != null) {
        final JSGraphQLEndpoint selectedEndpoint = endpointsModel.getSelectedItem();
        if (selectedEndpoint != null && selectedEndpoint.url != null) {
            final JSGraphQLQueryContext context = JSGraphQLQueryContextHighlightVisitor
                    .getQueryContextBufferAndHighlightUnused(editor);
            final Map<String, Object> requestData = Maps.newLinkedHashMap();
            requestData.put("query", context.query);
            try {
                requestData.put("variables", getQueryVariables(editor));
            } catch (JsonSyntaxException jse) {
                if (myToolWindowManagerInitialized) {
                    myToolWindowManager.logCurrentErrors(ContainerUtil.immutableList(
                            new JSGraphQLErrorResult("Failed to parse variables as JSON: " + jse.getMessage(),
                                    virtualFile.getPath(), "Error", 0, 0)),
                            true);/*from w w w .  j  a  v a 2 s. c  o  m*/
                }
                return;
            }
            final String requestJson = new Gson().toJson(requestData);
            final HttpClient httpClient = new HttpClient(new HttpClientParams());
            try {
                final PostMethod method = new PostMethod(selectedEndpoint.url);
                setHeadersFromOptions(selectedEndpoint, method);
                method.setRequestEntity(new StringRequestEntity(requestJson, "application/json", "UTF-8"));
                ApplicationManager.getApplication().executeOnPooledThread(() -> {
                    try {
                        try {
                            editor.putUserData(JS_GRAPH_QL_EDITOR_QUERYING, true);
                            StopWatch sw = new StopWatch();
                            sw.start();
                            httpClient.executeMethod(method);
                            final String responseJson = Optional.fromNullable(method.getResponseBodyAsString())
                                    .or("");
                            sw.stop();
                            final Integer errorCount = getErrorCount(responseJson);
                            if (fileEditor instanceof TextEditor) {
                                final TextEditor textEditor = (TextEditor) fileEditor;
                                UIUtil.invokeLaterIfNeeded(() -> {
                                    ApplicationManager.getApplication().runWriteAction(() -> {
                                        final Document document = textEditor.getEditor().getDocument();
                                        document.setText(responseJson);
                                        if (requestJson.startsWith("{")) {
                                            final PsiFile psiFile = PsiDocumentManager.getInstance(myProject)
                                                    .getPsiFile(document);
                                            if (psiFile != null) {
                                                new ReformatCodeProcessor(psiFile, false).run();
                                            }
                                        }
                                    });
                                    final StringBuilder queryResultText = new StringBuilder(
                                            virtualFile.getName()).append(": ").append(sw.getTime())
                                                    .append(" ms execution time, ")
                                                    .append(bytesToDisplayString(responseJson.length()))
                                                    .append(" response");

                                    if (errorCount != null && errorCount > 0) {
                                        queryResultText.append(", ").append(errorCount).append(" error")
                                                .append(errorCount > 1 ? "s" : "");
                                        if (context.onError != null) {
                                            context.onError.run();
                                        }
                                    }

                                    queryResultLabel.setText(queryResultText.toString());
                                    queryResultLabel.putClientProperty(FILE_URL_PROPERTY, virtualFile.getUrl());
                                    if (!queryResultLabel.isVisible()) {
                                        queryResultLabel.setVisible(true);
                                    }

                                    querySuccessLabel.setVisible(errorCount != null);
                                    if (querySuccessLabel.isVisible()) {
                                        if (errorCount == 0) {
                                            querySuccessLabel
                                                    .setBorder(BorderFactory.createEmptyBorder(2, 8, 0, 0));
                                            querySuccessLabel.setIcon(AllIcons.General.InspectionsOK);
                                        } else {
                                            querySuccessLabel
                                                    .setBorder(BorderFactory.createEmptyBorder(2, 12, 0, 4));
                                            querySuccessLabel.setIcon(AllIcons.Ide.ErrorPoint);
                                        }
                                    }
                                    showToolWindowContent(myProject, fileEditor.getComponent().getClass());
                                    textEditor.getEditor().getScrollingModel().scrollVertically(0);
                                });
                            }
                        } finally {
                            editor.putUserData(JS_GRAPH_QL_EDITOR_QUERYING, null);
                        }
                    } catch (IOException e) {
                        Notifications.Bus.notify(
                                new Notification("GraphQL", "GraphQL Query Error",
                                        selectedEndpoint.url + ": " + e.getMessage(), NotificationType.WARNING),
                                myProject);
                    }
                });
            } catch (UnsupportedEncodingException | IllegalStateException | IllegalArgumentException e) {
                Notifications.Bus.notify(
                        new Notification("GraphQL", "GraphQL Query Error",
                                selectedEndpoint.url + ": " + e.getMessage(), NotificationType.ERROR),
                        myProject);
            }

        }
    }
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

private static void initializeCSE(String authtoken, String cseName) throws IOException {
    HttpClient client = new HttpClient();

    //First perform the ClientLogin to get the authtoken
    //See http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html

    PostMethod create_post = new PostMethod("http://www.google.com/cse/api/default/cse/" + cseName);

    String new_annotation = "<CustomSearchEngine language=\"en\">" + "<Title>" + Util.escapeXML(cseName)
            + "</Title>" + "<Description>" + Util.escapeXML(cseName) + " - generated by Slant</Description>"
            + "<Context>" + "<BackgroundLabels>" + "<Label name=\"_cse_testengine\" mode=\"BOOST\" />"
            + "<Label name=\"_cse_exclude_testengine\" mode=\"ELIMINATE\" />" +
            //   "<Label name=\"high\" mode=\"BOOST\" weight=\"1.0\"/>" +
            //   "<Label name=\"medium\" mode=\"BOOST\" weight=\"0.8\"/>" +
            //   "<Label name=\"low\" mode=\"BOOST\" weight=\"0.1\"/>" +
            "</BackgroundLabels>" + "</Context>" + "<LookAndFeel nonprofit=\"true\" />"
            + "<ImageSearchSettings enable=\"true\" />" + "</CustomSearchEngine>";

    create_post.addRequestHeader("Content-type", "text/xml");
    create_post.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);

    StringRequestEntity rq_en = new StringRequestEntity(new_annotation, "text/xml", "UTF-8");
    create_post.setRequestEntity(rq_en);
    //      PostMethod create_post = new PostMethod("http://www.google.com/cse/api/default/cse/testengine");

    /*//from   w  ww  .  j  a v a  2 s.  co m
          String new_annotation ="<CustomSearchEngine  language=\"en\">" +
    "<Title> CSE </Title>" + 
    "<Description>Custom Search</Description>" + 
    "<Context>" +
    "<BackgroundLabels>"+
    "<Label name=\"_cse_testengine\" mode=\"FILTER\" />"+
    "<Label name=\"_cse_exclude_testengine\" mode=\"ELIMINATE\" />"+
    "<Label name=\"high\" mode=\"BOOST\" weight=\"1.0\"/>" +
    "<Label name=\"medium\" mode=\"BOOST\" weight=\"0.8\"/>" +
    "<Label name=\"low\" mode=\"BOOST\" weight=\"0.1\"/>" +
    "</BackgroundLabels>"+
    "</Context>"+
    "<LookAndFeel nonprofit=\"false\" />"+
    "</CustomSearchEngine>";
            
          create_post.addRequestHeader("Content-type", "text/xml");
          create_post.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);
            
          StringRequestEntity rq_en = new StringRequestEntity(new_annotation,"text/xml","UTF-8");
          create_post.setRequestEntity(rq_en);
    */

    int astatusCode = client.executeMethod(create_post);

    if (astatusCode == HttpStatus.SC_OK) {
        log.info("CSE " + cseName + " created");
        //If successful, the CSE annotation is displayed in the response.
        log.info(create_post.getResponseBodyAsString());
    } else
        log.warn("CSE " + cseName + " creation failed");
}

From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java

@Override
public final ScribeCommandObject createObject(final ScribeCommandObject cADCommandObject) throws Exception {
    logger.debug("----Inside createObject");
    PostMethod postMethod = null;//from   ww  w  .j  ava  2s  . c  om
    try {

        String serviceURL = null;
        String serviceProtocol = null;
        String userId = null;
        String password = null;
        String sessionId = null;
        String crmPort = "80";

        /* Check if CrmUserId is present in request */
        if (cADCommandObject.getCrmUserId() != null) {

            /* Get agent from session manager */
            final ScribeCacheObject agent = zDCRMSessionManager
                    .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

            /* Get CRM information from agent */
            serviceURL = agent.getScribeMetaObject().getCrmServiceURL();
            serviceProtocol = agent.getScribeMetaObject().getCrmServiceProtocol();
            userId = agent.getScribeMetaObject().getCrmUserId();
            password = agent.getScribeMetaObject().getCrmPassword();
            sessionId = agent.getScribeMetaObject().getCrmSessionId();
            crmPort = agent.getScribeMetaObject().getCrmPort();
        }

        /* Create Zen desk URL */
        final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/" + cADCommandObject.getObjectType()
                + "s.xml";

        logger.debug("----Inside createObject zenDeskURL: " + zenDeskURL);

        /* Instantiate get method */
        postMethod = new PostMethod(zenDeskURL);

        /* Set request content type */
        postMethod.addRequestHeader("Content-Type", "application/xml");
        postMethod.addRequestHeader("accept", "application/xml");

        /* Cookie is required to be set for session management */
        postMethod.addRequestHeader("Cookie", sessionId);

        /* Add request entity */
        final RequestEntity entity = new StringRequestEntity(
                ZDCRMMessageFormatUtils.getCreateRequestXML(cADCommandObject), null, null);
        postMethod.setRequestEntity(entity);

        final HttpClient httpclient = new HttpClient();

        /* Set credentials */
        httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)),
                new UsernamePasswordCredentials(userId, password));

        /* Execute method */
        int result = httpclient.executeMethod(postMethod);
        logger.debug("----Inside createObject response code: " + result + " & body: "
                + postMethod.getResponseBodyAsString());

        /* Check if object is created */
        if (result == HttpStatus.SC_OK || result == HttpStatus.SC_CREATED) {

            /* Trick: ZD does not gives object in create response */
            /* TODO: Read the newly created ZD object using search */
            return cADCommandObject;
        } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED
                || result == HttpStatus.SC_NOT_ACCEPTABLE) {
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : "
                    + ZDCRMMessageFormatUtils.getErrorFromResponse(postMethod.getResponseBodyAsStream()));
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM");
        } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {
            throw new ScribeException(ScribeResponseCodes._1004
                    + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct");
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final ParserConfigurationException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final SAXException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } finally {
        /* Release connection socket */
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}

From source file:com.wso2telco.openidtokenbuilder.MIFEOpenIDTokenBuilder.java

/**
 * Gets the ACR app id./*from ww  w  . jav a2  s .c  om*/
 *
 * @param applicationName the application name
 * @return the ACR app id
 * @throws IdentityOAuth2Exception the identity o auth2 exception
 */
public String getACRAppID(String applicationName) throws IdentityOAuth2Exception {
    StringBuilder requestURLBuilder = new StringBuilder();
    requestURLBuilder.append(ACR_HOST_URI);
    requestURLBuilder.append("/"); //$NON-NLS-1$
    requestURLBuilder.append(APP_PROV_SERVICE);
    requestURLBuilder.append("/"); //$NON-NLS-1$
    requestURLBuilder.append(SERVICE_PROVIDER);
    String requestURL = requestURLBuilder.toString();

    JSONObject requestBody = new JSONObject();
    JSONObject createRequest = null;

    try {
        requestBody.put("appName", applicationName); //$NON-NLS-1$
        requestBody.put("serviceProviderAppId", applicationName); //$NON-NLS-1$
        requestBody.put("description", applicationName + " description"); //$NON-NLS-1$ //$NON-NLS-2$
        createRequest = new JSONObject().put("provisionAppRequest", requestBody); //$NON-NLS-1$
        StringRequestEntity requestEntity = new StringRequestEntity(createRequest.toString(),
                "application/json", "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
        PostMethod postMethod = new PostMethod(requestURL);
        postMethod.addRequestHeader("Authorization-ACR", "ServiceKey " + SERVICE_KEY); //$NON-NLS-1$ //$NON-NLS-2$
        postMethod.addRequestHeader("Authorization", "Bearer " + ACR_ACCESS_TOKEN); //$NON-NLS-1$ //$NON-NLS-2$
        postMethod.setRequestEntity(requestEntity);

        if (DEBUG) {
            log.debug("Connecting to ACR engine @ " + ACR_HOST_URI); //$NON-NLS-1$
            log.debug("Service name : " + APP_PROV_SERVICE); //$NON-NLS-1$
            log.debug("Service provider : " + SERVICE_PROVIDER); //$NON-NLS-1$
            log.debug("Request - ACR app : " + requestEntity.getContent()); //$NON-NLS-1$
        }

        httpClient = new HttpClient();
        httpClient.executeMethod(postMethod);

        String responseACRApp = new String(postMethod.getResponseBody(), "UTF-8"); //$NON-NLS-1$
        String strACR = ""; //$NON-NLS-1$
        if (null != responseACRApp && !"".equals(responseACRApp)) { //$NON-NLS-1$
            try {
                if (DEBUG) {
                    log.debug("Response - ACR app : " + responseACRApp); //$NON-NLS-1$
                }
                strACR = JsonPath.read(responseACRApp, "$.provisionAppResponse.appID"); //$NON-NLS-1$
            } catch (Exception e) {
                log.error("Provisioning of ACR app failed", e); //$NON-NLS-1$
                throw new IdentityOAuth2Exception("Provisioning of ACR app failed", e); //$NON-NLS-1$
            }
        }

        return strACR; //$NON-NLS-1$;

    } catch (UnsupportedEncodingException e) {
        log.error("Error occured while creating request", e); //$NON-NLS-1$
        throw new IdentityOAuth2Exception("Error occured while creating request", e); //$NON-NLS-1$
    } catch (JSONException e) {
        log.error("Error occured while creating request", e); //$NON-NLS-1$
        throw new IdentityOAuth2Exception("Error occured while creating request", e); //$NON-NLS-1$
    } catch (HttpException e) {
        log.error("Error occured while creating ACR app", e); //$NON-NLS-1$
        throw new IdentityOAuth2Exception("Error occured while creating ACR app", e); //$NON-NLS-1$
    } catch (IOException e) {
        log.error("Error occured while creating ACR app", e); //$NON-NLS-1$
        throw new IdentityOAuth2Exception("Error occured while creating ACR app", e); //$NON-NLS-1$
    }
}

From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java

public String updateClientApp(String clientId, String scope, String description, Integer status,
        String redirectUri) {/*from   w w w  .j a v a2 s  . c  o  m*/
    PutMethod put = new PutMethod(baseOAuth20Uri + APPLICATION_ENDPOINT + "/" + clientId);
    String response = null;
    try {
        //put.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(clientId));
        JSONObject json = new JSONObject();
        json.put("status", status);
        json.put("description", description);
        json.put("redirect_uri", redirectUri);
        String requestBody = json.toString();
        RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8");
        put.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        put.setRequestEntity(requestEntity);
        response = readResponse(put);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot update client app", e);
    } catch (JSONException e) {
        log.error("cannot update client app", e);
    }
    return response;
}

From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java

public String updateClientAppStatus(String clientId, Integer status) {
    PutMethod put = new PutMethod(baseOAuth20Uri + APPLICATION_ENDPOINT + "/" + clientId);
    String response = null;//w w w. j  av a2 s  . c om
    try {
        //put.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(clientId));
        JSONObject json = new JSONObject();
        json.put("status", status);
        String requestBody = json.toString();
        RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8");
        put.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        put.setRequestEntity(requestEntity);
        response = readResponse(put);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot update client app", e);
    } catch (JSONException e) {
        log.error("cannot update client app", e);
    }
    return response;
}

From source file:com.xmlcalabash.library.HttpRequest.java

private void doPutOrPostSinglepart(EntityEnclosingMethod method, XdmNode body) {
    // ATTENTION: This doesn't handle multipart, that's done entirely separately

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Check for consistency of content-type
    contentType = body.getAttributeValue(_content_type);
    if (contentType == null) {
        throw new XProcException(step.getNode(), "Content-type on c:body is required.");
    }//  www. jav  a 2  s .  c  o  m

    if (headerContentType != null && !headerContentType.equals(contentType.toLowerCase())) {
        throw XProcException.stepError(20);
    }

    for (Header header : headers) {
        method.addRequestHeader(header);
    }

    // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it
    String postContent = null;
    String encoding = body.getAttributeValue(_encoding);
    try {
        if ("base64".equals(encoding)) {
            String charset = body.getAttributeValue(_charset);
            // FIXME: is utf-8 the right default?
            if (charset == null) {
                charset = "utf-8";
            }
            String escapedContent = decodeBase64(body, charset);
            StringWriter writer = new StringWriter();
            writer.write(escapedContent);
            writer.close();
            postContent = writer.toString();
        } else {
            if (jsonContentType(contentType)) {
                postContent = XMLtoJSON.convert(body);
            } else if (xmlContentType(contentType)) {
                Serializer serializer = makeSerializer();

                if (!S9apiUtils.isDocumentContent(body.axisIterator(Axis.CHILD))) {
                    throw XProcException.stepError(22);
                }

                Vector<XdmNode> content = new Vector<XdmNode>();
                XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
                while (iter.hasNext()) {
                    XdmNode node = (XdmNode) iter.next();
                    content.add(node);
                }

                // FIXME: set serializer properties appropriately!
                StringWriter writer = new StringWriter();
                serializer.setOutputWriter(writer);
                S9apiUtils.serialize(runtime, content, serializer);
                writer.close();
                postContent = writer.toString();
            } else {
                StringWriter writer = new StringWriter();
                XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
                while (iter.hasNext()) {
                    XdmNode node = (XdmNode) iter.next();
                    if (node.getNodeKind() != XdmNodeKind.TEXT) {
                        throw XProcException.stepError(28);
                    }
                    writer.write(node.getStringValue());
                }
                writer.close();
                postContent = writer.toString();
            }
        }

        StringRequestEntity requestEntity = new StringRequestEntity(postContent, contentType, "UTF-8");
        method.setRequestEntity(requestEntity);

    } catch (IOException ioe) {
        throw new XProcException(ioe);
    } catch (SaxonApiException sae) {
        throw new XProcException(sae);
    }
}