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:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void sendNotification(Notification notification, int instanceId, int learningObjectId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Notification",
            learningObjectId, instanceId);
    PostMethod method = (PostMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.POST);
    String reportAsXml = serializeNotificationToXML(notification);
    InputStream is = new ByteArrayInputStream(reportAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {/*from ww w  . jav a  2  s.com*/
        int statusCode = _httpClient.executeMethod(method);
        // POST methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST
 * data as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                               configuring to send a multipart POST request
 * @param httpServletRequest     The {@link HttpServletRequest} that contains
 *                               the mutlipart POST data to be sent via the {@link PostMethod}
 * @throws javax.servlet.ServletException If something fails when uploading the content to the server
 *//*from w ww  .ja va 2s .  c o  m*/
@SuppressWarnings({ "unchecked", "ToArrayCallWithZeroLengthArrayArgument" })
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectInstanceUserReports(List<LearningObjectInstanceUserReport> userReports,
        int instanceId, int learningObjectId) throws Exception {
    String uri = String.format(_baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Reports",
            learningObjectId, instanceId);
    PostMethod method = (PostMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.POST);
    String reportsAsXml = serializeLearningObjectInstanceUserReportsToXML(userReports);
    InputStream is = new ByteArrayInputStream(reportsAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {//from  w w w . j a va  2  s  . c om
        int statusCode = _httpClient.executeMethod(method);
        // POST methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are
 *                               configuring to send a multipart POST request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the mutlipart POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *//*from  w  w w.ja  v  a  2s.c  om*/
@SuppressWarnings("unchecked")
private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams());
        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

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;
    try {/*  www.j a  v a  2  s  .  com*/

        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.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;
    try {//from www  . j  a v  a2s.  c o m

        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.apatar.rss.RssNode.java

private void publishing() throws HttpException, IOException, ApatarException {
    Object obj = ApplicationData.getProject().getProjectData(getConnectionDataID()).getData();
    if (!(obj instanceof CreateNewParams)) {
        return;/*w  w w . java 2 s. c om*/
    }

    CreateNewParams params = (CreateNewParams) obj;

    PostMethod method = new PostMethod(PUBLISH_URL);

    String tempFolderName = "publish/";
    File tempFolder = new File(tempFolderName);
    if (!tempFolder.exists()) {
        tempFolder.mkdir();
    }
    String fileName = rssTitle == null ? "temp" : rssTitle.replaceAll("[|/\\:*?\"<> ]", "_") + ".aptr";
    ReadWriteXMLDataUi rwXMLdata = new ReadWriteXMLDataUi();
    File tempFile = rwXMLdata.writeXMLData(fileName.toString(), ApplicationData.getProject(), true);

    int partCount = 15;
    if (publishId != null) {
        partCount++;
    }
    Part[] parts = new Part[partCount];
    parts[0] = new StringPart("option", "com_remository");
    parts[1] = new StringPart("task", "");
    parts[2] = new StringPart("element", "component");
    parts[3] = new StringPart("client", "");
    parts[4] = new StringPart("oldid", "0");
    parts[5] = new FilePart("userfile", tempFile);
    parts[6] = new StringPart("containerid", "15");
    parts[7] = new StringPart("filetitle", rssTitle == null ? "" : rssTitle);
    parts[8] = new StringPart("description", description == null ? "" : description);
    parts[9] = new StringPart("smalldesc", description == null ? "" : description);
    parts[10] = new StringPart("filetags", "RSS");
    parts[11] = new StringPart("pubExternal", "true");
    parts[12] = new StringPart("username", username);
    parts[13] = new StringPart("password", CoreUtils.getMD5(password));
    parts[14] = new FilePart("rssfile", params.getFile());
    if (publishId != null) {
        parts[15] = new StringPart("dmid", publishId);
    }

    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                "Upload failed, response=" + HttpStatus.getStatusText(status));
    } else {
        if (publishId == null) {
            StringBuffer buff = new StringBuffer(method.getResponseBodyAsString());

            Matcher matcher = ApatarRegExp.getMatcher("<meta name=\"dmid\" content=\"[a-zA-Z_0-9]+\"",
                    buff.toString());

            while (matcher.find()) {
                String result = matcher.group();
                if (result == null || result.equals("")) {
                    JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Publishing error");
                    return;
                }
                result = result.replaceFirst("<meta name=\"dmid\" content=\"", "");
                result = result.replace("\"", "");
                publishId = result;
                return;
            }
        }
        JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Publishing error");
    }
}

From source file:edu.harvard.iq.dvn.core.web.dataaccess.HttpAccessObject.java

private String dvnRemoteAuth(String remoteHost) {
    // if successful, this method will return the JSESSION string
    // for the authenticated session on the remote DVN.

    String remoteJsessionid = null;
    String remoteDvnUser = null;/* w  w w  .j ava  2  s  .  c  o m*/
    String remoteDvnPw = null;

    GetMethod loginGetMethod = null;
    PostMethod loginPostMethod = null;

    RemoteAccessAuth remoteAuth = studyService.lookupRemoteAuthByHost(remoteHost);

    if (remoteAuth == null) {
        return null;
    }

    remoteDvnUser = remoteAuth.getAuthCred1();
    remoteDvnPw = remoteAuth.getAuthCred2();

    if (remoteDvnUser == null || remoteDvnPw == null) {
        return null;
    }

    int status = 0;

    try {

        String remoteAuthUrl = "http://" + remoteHost + "/dvn/faces/login/LoginPage.xhtml";
        loginGetMethod = new GetMethod(remoteAuthUrl);
        loginGetMethod.setFollowRedirects(false);
        status = (new HttpClient()).executeMethod(loginGetMethod);

        InputStream in = loginGetMethod.getResponseBodyAsStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(in));

        String line = null;

        String viewstate = null;

        String regexpJsession = "jsessionid=([^\"?&]*)";
        String regexpViewState = "ViewState\" value=\"([^\"]*)\"";

        Pattern patternJsession = Pattern.compile(regexpJsession);
        Pattern patternViewState = Pattern.compile(regexpViewState);

        Matcher matcher = null;

        while ((line = rd.readLine()) != null) {
            matcher = patternJsession.matcher(line);
            if (matcher.find()) {
                remoteJsessionid = matcher.group(1);
            }
            matcher = patternViewState.matcher(line);
            if (matcher.find()) {
                viewstate = matcher.group(1);
            }
        }

        rd.close();
        loginGetMethod.releaseConnection();

        if (remoteJsessionid != null) {

            // We have found Jsession;
            // now we can log in,
            // has to be a POST method:

            loginPostMethod = new PostMethod(remoteAuthUrl + ";jsessionid=" + remoteJsessionid);
            loginPostMethod.setFollowRedirects(false);

            Part[] parts = { new StringPart("vanillaLoginForm:vdcId", ""),
                    new StringPart("vanillaLoginForm:username", remoteDvnUser),
                    new StringPart("vanillaLoginForm:password", remoteDvnPw),
                    new StringPart("vanillaLoginForm_hidden", "vanillaLoginForm_hidden"),
                    new StringPart("vanillaLoginForm:button1", "Log in"),
                    new StringPart("javax.faces.ViewState", viewstate) };

            loginPostMethod.setRequestEntity(new MultipartRequestEntity(parts, loginPostMethod.getParams()));
            loginPostMethod.addRequestHeader("Cookie", "JSESSIONID=" + remoteJsessionid);
            status = (new HttpClient()).executeMethod(loginPostMethod);

            String redirectLocation = null;

            if (status == 302) {
                for (int i = 0; i < loginPostMethod.getResponseHeaders().length; i++) {
                    String headerName = loginPostMethod.getResponseHeaders()[i].getName();
                    if (headerName.equals("Location")) {
                        redirectLocation = loginPostMethod.getResponseHeaders()[i].getValue();
                    }
                }
            }

            loginPostMethod.releaseConnection();
            int counter = 0;

            int redirectLimit = 20; // number of redirects we are willing to follow before we give up.

            while (status == 302 && counter < redirectLimit) {

                if (counter > 0) {
                    for (int i = 0; i < loginGetMethod.getResponseHeaders().length; i++) {
                        String headerName = loginGetMethod.getResponseHeaders()[i].getName();
                        if (headerName.equals("Location")) {
                            redirectLocation = loginGetMethod.getResponseHeaders()[i].getValue();
                        }
                    }
                }

                // try following redirects until we get a static page,
                // or until we exceed the hoop limit.
                if (redirectLocation.matches(".*TermsOfUsePage.*")) {
                    loginGetMethod = remoteAccessTOU(redirectLocation + "&clicker=downloadServlet",
                            remoteJsessionid, null, null);
                    if (loginGetMethod != null) {
                        status = loginGetMethod.getStatusCode();
                    }
                } else {
                    loginGetMethod = new GetMethod(redirectLocation);
                    loginGetMethod.setFollowRedirects(false);
                    loginGetMethod.addRequestHeader("Cookie", "JSESSIONID=" + remoteJsessionid);
                    status = (new HttpClient()).executeMethod(loginGetMethod);

                    //InputStream in = loginGetMethod.getResponseBodyAsStream();
                    //BufferedReader rd = new BufferedReader(new InputStreamReader(in));
                    //rd.close();
                    loginGetMethod.releaseConnection();
                    counter++;
                }
            }
        }
    } catch (IOException ex) {
        if (loginGetMethod != null) {
            loginGetMethod.releaseConnection();
        }
        if (loginPostMethod != null) {
            loginPostMethod.releaseConnection();
        }
        return null;
    }

    return remoteJsessionid;
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void sendNotificationToUsers(Notification notification, int learningObjectId, int instanceId,
        int[] receiverUserIds, int senderUserId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/NotificationToUsers",
            learningObjectId, instanceId);
    PostMethod method = (PostMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.POST);
    String reportAsXml = serializeNotificationToWrappedXML(notification);
    String userIdsAsXml = serializeUserIdsToWrappedXML(receiverUserIds);
    String senderUserIdAsXml = "<senderUserId>" + Integer.toString(senderUserId) + "</senderUserId>";
    String openingTag = "<SendNotificationToUsers xmlns=\"http://tempuri.org/\">";
    String closingTag = "</SendNotificationToUsers>";

    StringBuilder xmlBuilder = new StringBuilder();
    xmlBuilder.append(openingTag);//from ww  w .  j  a va 2  s  .c o  m
    xmlBuilder.append(reportAsXml);
    xmlBuilder.append(userIdsAsXml);
    xmlBuilder.append(senderUserIdAsXml);
    xmlBuilder.append(closingTag);

    method.setRequestEntity(new StringRequestEntity(xmlBuilder.toString(), "text/xml", "UTF-8"));

    try {
        int statusCode = _httpClient.executeMethod(method);
        // POST methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

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

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

    // Get capturable transaction
    PostMethod httppost = null;

    try {/* ww w . j av a2 s.c  o m*/

        // determine production - test environment

        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();
        }

        // Protocol easyhttps = new Protocol("https", new
        // EasySSLProtocolSocketFactory(), 443);
        HttpClient client = new HttpClient();

        String xml = "<?xml version=\"1.0\"?><AddressValidationRequest xml:lang=\"en-US\"><Request><TransactionReference><CustomerContext>SalesManager Data</CustomerContext><XpciVersion>1.0001</XpciVersion></TransactionReference><RequestAction>AV</RequestAction></Request>";
        StringBuffer xmldatabuffer = new StringBuffer();
        xmldatabuffer.append("<Order>");
        xmldatabuffer.append("<StoreID>").append(ik.getUserid()).append("</StoreID>");
        xmldatabuffer.append("<Passphrase>").append(ik.getTransactionKey()).append("</Passphrase>");
        xmldatabuffer.append("<PaymentType>").append("CC").append("</PaymentType>");

        // 0=Sale, 1=PreAuth, 2=PostAuth, 3=Credit, 4=Forced PostAuth

        xmldatabuffer.append("<CardAction>").append("2").append("</CardAction>");
        // For postauth only
        xmldatabuffer.append("<OrderID>").append(trx.getInternalGatewayOrderId()).append("</OrderID>");
        xmldatabuffer.append("</Order>");
        /**
         * xmldatabuffer.append("<CardNumber>").append("").append(
         * "</CardNumber>");
         * xmldatabuffer.append("<CardExpMonth>").append(""
         * ).append("</CardExpMonth>");
         * xmldatabuffer.append("<CardExpYear>")
         * .append("").append("</CardExpYear>"); //CVV
         * xmldatabuffer.append("<CustomerIP>"
         * ).append("").append("</CustomerIP>");
         * xmldatabuffer.append("<CardIDNumber>"
         * ).append("").append("</CardIDNumber>");
         * xmldatabuffer.append("</Order>");
         **/

        log.debug("Psigate request " + xmldatabuffer.toString());

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

        PsigateParsedElements pe = null;
        String stringresult = null;

        int result = client.executeMethod(httppost);
        if (result != 200) {
            log.error("Communication Error with psigate " + protocol + "://" + host + ":" + port + url);
            throw new Exception(
                    "Communication Error with psigate " + protocol + "://" + host + ":" + port + url);
        }
        stringresult = httppost.getResponseBodyAsString();
        log.debug("Psigate response " + stringresult);

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

        digester.addCallMethod("Result/OrderID", "setOrderID", 0);
        digester.addCallMethod("Result/Approved", "setApproved", 0);
        digester.addCallMethod("Result/ErrMsg", "setErrMsg", 0);
        digester.addCallMethod("Result/ReturnCode", "setReturnCode", 0);
        digester.addCallMethod("Result/TransRefNumber", "setTransRefNumber", 0);
        digester.addCallMethod("Result/CardType", "setCardType", 0);

        Reader reader = new StringReader(stringresult);

        digester.parse(reader);

        return this.parseResponse(PaymentConstants.CAPTURE, xmldatabuffer.toString(), stringresult, pe, order,
                order.getTotal());

    } catch (Exception e) {
        if (e instanceof TransactionException) {
            throw (TransactionException) e;
        }
        log.error(e);
        TransactionException te = new TransactionException("Psigate Gateway error ", e);
        te.setErrorcode("01");
        throw te;
    } finally {
        if (httppost != null)
            httppost.releaseConnection();
    }

}