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

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

Introduction

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

Prototype

public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException 

Source Link

Usage

From source file:org.gc.googleAnalytics.PostData.java

/**
 * Executes post request to collect data on Exception Tracking
 * in owner google analytics account.//from   w w  w . jav a2 s.c om
 * 
 * @param description : String
 * @param fatal : String
 * @return boolean value, if request is ok then true else false.
 */
public boolean exceptionTracking(String description, boolean fatal) {
    //check input parameter
    if (description == null) {
        logger.error("In Exception Tracking, Description is required.");
        return false;
    }
    // set request
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(ENDPOINT);
    method.addParameter(PROTOCAL_VERSION, "1");
    method.addParameter(TRACKING_ID, trackingID);
    method.addParameter(CLIENT_ID, clientID);
    method.addParameter(HIT_TYPE, "exception");
    method.addParameter(APPLICATION_NAME, appName);
    method.addParameter(APPLICATION_VERSION,
            (!(this.appVersion == null || this.appVersion.length() == 0)) ? this.appVersion : DEFAULT_VERSION);
    method.addParameter(EXP_DESCRIPTION, description);
    method.addParameter(EXP_ISFATAL, "" + fatal);
    try {
        // execute request
        int returnCode = client.executeMethod(method);
        return (returnCode == HttpStatus.SC_OK);

    } catch (Exception e) {
        logger.error("ERROR: {}", e.getMessage());
        return false;

    }
}

From source file:org.genedb.web.mvc.controller.SequenceDistributorController.java

private String post(String uri, Map<String, String> parameters) {
    final PostMethod postMethod = new PostMethod(uri);

    logger.debug(uri);// w  ww. j av  a2  s  .  com

    for (Entry<String, String> entry : parameters.entrySet()) {
        //          logger.error(entry.getKey());
        //          logger.error(entry.getValue());
        postMethod.addParameter(entry.getKey(), entry.getValue());
    }

    HttpClient client = new HttpClient();

    int statusCode;
    try {
        statusCode = client.executeMethod(postMethod);

        if (statusCode == HttpStatus.SC_OK) {
            final InputStream responseBodyStream = postMethod.getResponseBodyAsStream();
            StringWriter writer = new StringWriter();
            IOUtils.copy(responseBodyStream, writer);

            responseBodyStream.close();

            return writer.toString();

        }

    } catch (HttpException e) {
        logger.error(e);
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e);
        e.printStackTrace();
    }

    return "Sorry but could not prepare the BLAST form. Please contact webmaster@genedb.org with information on the gene that caused this problem.";
}

From source file:org.glite.slcs.shibclient.ShibbolethClient.java

/**
 * Processes the IdP response as a Browser/POST
 * /*ww  w  .  jav  a 2 s .  co m*/
 * @param idp
 *            The {@link IdentityProvider}.
 * @param idpSSOResponseURI
 *            The IdP SSO reponse {@link URI}.
 * @return the SP URI to go to
 * @throws RemoteException
 */
private URI processIdPBrowserPOST(IdentityProvider idp, URI idpSSOResponseURI, InputStream htmlStream)
        throws RemoteException {
    // return value
    URI browserPostResponseURI = null;
    RemoteException remoteException = null;

    try {
        Source source = new Source(htmlStream);
        List<Element> forms = source.findAllElements(Tag.FORM);
        if (!forms.isEmpty()) {
            // check if form contains a valid SAML Browser/POST
            for (Element form : forms) {
                String spSAMLURL = form.getAttributeValue("ACTION");
                LOG.debug("SAML Browser/POST URL=" + spSAMLURL);
                if (spSAMLURL == null) {
                    // no SAML post URL found
                    String htmlBody = inputStreamToString(htmlStream);
                    LOG.error("No SAML Browser/POST FORM ACTION found: " + idpSSOResponseURI + ": " + htmlBody);
                    remoteException = new RemoteException("No SAML Browser/POST FORM ACTION found: "
                            + idpSSOResponseURI + ". Please see the log file.");

                    break; // exit loop
                }

                // create POST method
                PostMethod postSPSAMLMethod = new PostMethod(spSAMLURL);
                // add all HIDDEN fields to POST
                List<FormControl> formControls = form.findFormControls();
                for (FormControl control : formControls) {
                    FormControlType type = control.getFormControlType();
                    if (type.equals(FormControlType.HIDDEN)) {
                        String name = control.getName();
                        Collection<CharSequence> values = control.getValues();
                        for (CharSequence value : values) {
                            LOG.debug("HIDDEN " + name + "=" + value);
                            // add all hidden fields
                            postSPSAMLMethod.addParameter(name, (String) value);
                        }
                    }
                }

                // execute the SAML post
                LOG.info("POST SPSAMLMethod: " + postSPSAMLMethod.getURI());
                int spSAMLResponseStatus = executeMethod(postSPSAMLMethod);
                LOG.debug(postSPSAMLMethod.getStatusLine());

                // status must be 302 and redirect Location
                Header location = postSPSAMLMethod.getResponseHeader("Location");
                if (spSAMLResponseStatus == 302 && location != null) {
                    String url = location.getValue();
                    browserPostResponseURI = new URI(url, false);
                    LOG.debug("Redirect: " + browserPostResponseURI);

                } else {
                    LOG.error(
                            "Unexpected SP response: Status=" + spSAMLResponseStatus + " Location=" + location);
                    remoteException = new RemoteException(
                            "Unexpected SP response: Status=" + spSAMLResponseStatus + " Location=" + location);
                }

                LOG.trace("postSPSAMLMethod.releaseConnection()");
                postSPSAMLMethod.releaseConnection();

            } // forms loop
        } else {
            // no SAML post found
            String htmlBody = inputStreamToString(htmlStream);
            LOG.error("No SAML Browser/POST profile found: " + idpSSOResponseURI + ": " + htmlBody);
            remoteException = new RemoteException(
                    "No SAML Browser/POST profile found: " + idpSSOResponseURI + ". Please see the log file.");
        }

    } catch (URIException e) {
        e.printStackTrace();
        remoteException = new RemoteException(e.getMessage(), e);
    } catch (IOException e) {
        e.printStackTrace();
        remoteException = new RemoteException(e.getMessage(), e);
    }

    if (browserPostResponseURI == null) {
        if (remoteException != null) {
            throw remoteException;
        }
    }

    return browserPostResponseURI;
}

From source file:org.glite.slcs.shibclient.ShibbolethClient.java

/**
 * @param idp/*from www  .jav a2 s  . c o  m*/
 * @param query
 * @throws URIException
 * @throws HttpException
 * @throws IOException
 * @throws AuthException
 * @throws RemoteException
 * @throws ServiceException
 */
private URI processIdPSSO(IdentityProvider idp, URI spResponseURI)
        throws URIException, HttpException, IOException, AuthException, RemoteException, ServiceException {
    String idpSSOURL = idp.getUrl();
    LOG.debug("IdP SSO URL: " + idpSSOURL);
    String spResponseURL = spResponseURI.getEscapedURI();
    LOG.debug("spResponseURL=" + spResponseURL);
    // check if the spResponseURL is not already the IdP SSO url
    if (spResponseURL.startsWith(idpSSOURL)) {
        idpSSOURL = spResponseURL;
    } else {
        // if not, build it
        // BUG FIX: Shib SP 2.0 send the ?service=... in the query
        String query = spResponseURI.getEscapedQuery();
        LOG.debug("IdP SSO Query: " + query);
        if (query != null) {
            if (query.startsWith("service=")) {
                int i = query.indexOf("shire");
                if (i > 0) {
                    query = query.substring(i);
                    LOG.debug(
                            "IdP SSO Query contains the 'service=...' part, cutting up to 'shire=': " + query);
                } else {
                    LOG.error(
                            "IdP SSO Query contains the 'service=' parameter, but not the 'shire=' parameter: "
                                    + query);
                    throw new RemoteException(
                            "IdP SSO Query contains the 'service=' parameter, but not the 'shire=' parameter: "
                                    + query);
                }
            }
            // getIdpSSOMethod.setQueryString(query);
            idpSSOURL += "?" + query;
        }
        LOG.debug("IdP SSO URL (with query): " + idpSSOURL);
    }
    // create HttpMethod
    GetMethod getIdpSSOMethod = new GetMethod(idpSSOURL);

    URI idpSSOURI = getIdpSSOMethod.getURI();
    // set credential for basic or ntlm
    int authType = idp.getAuthType();
    LOG.debug("IdP authType: " + idp.getAuthTypeName());
    if (authType == IdentityProvider.SSO_AUTHTYPE_BASIC || authType == IdentityProvider.SSO_AUTHTYPE_NTLM) {
        // enable BASIC or NTLM authN
        AuthScope scope = new AuthScope(idpSSOURI.getHost(), idpSSOURI.getPort(), idp.getAuthRealm());
        LOG.info("Enable " + idp.getAuthTypeName() + " authentication: " + credentials_ + ", scope: " + scope);
        httpClient_.getState().setCredentials(scope, credentials_);
        getIdpSSOMethod.setDoAuthentication(true);
    }

    // execute the method
    LOG.info("GET IdpSSOMethod: " + idpSSOURI);
    int idpSSOResponseStatus = executeMethod(getIdpSSOMethod);
    String idpSSOResponseStatusLine = getIdpSSOMethod.getStatusLine().toString();
    LOG.debug(idpSSOResponseStatusLine);

    URI idpSSOResponseURI = getIdpSSOMethod.getURI();
    LOG.debug("idpSSOResponseURI=" + idpSSOResponseURI);
    String idpSSOResponseQuery = idpSSOResponseURI.getEscapedQuery();
    LOG.debug("idpSSOResponseQuery=" + idpSSOResponseQuery);

    // XXX
    dumpHttpClientCookies();

    LOG.debug("idpSSOResponseStatus=" + idpSSOResponseStatus);
    // BASIC or NTLM response handling
    if (idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_BASIC
            || idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_NTLM) {
        // !200 and same URL as before: if BASIC or NTLM failed on IdP

        LOG.debug("idpSSOURI=" + idpSSOURI);
        LOG.debug("idpSSOResponseURI=" + idpSSOResponseURI);

        if (idpSSOResponseStatus != 200 && idpSSOResponseURI.equals(idpSSOURI)) {

            LOG.trace("getIdpSSOMethod.releaseConnection()");
            getIdpSSOMethod.releaseConnection();

            LOG.error("BASIC or NTLM authentication was required for " + idpSSOURL);

            throw new AuthException(
                    idp.getAuthTypeName() + " authentication failed: " + idpSSOResponseStatusLine + " URL: "
                            + idpSSOResponseURI + " Credentials: " + this.credentials_);
        } else {
            // SAML/Artifact: idpSSOResponseURI is already SP login and the
            // XML <SLCSLoginResponse> is already there
            // XXX: resend to same IdP SSO page once again
            LOG.info("IdP BASIC or NTLM authN: resend again to the same IdP SSO URI: " + idpSSOURL);
            idpSSOResponseURI = new URI(idpSSOURL, false);
        }

    }
    // CAS sends 200 + Cookies and the login form directly
    else if (idpSSOResponseStatus == 200 && (idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_CAS
            || idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_FORM)) {
        LOG.debug("Process " + idp.getAuthTypeName() + " login form...");
        // process CAS login form
        InputStream idpLoginForm = getIdpSSOMethod.getResponseBodyAsStream();
        LOG.debug("idpSSOURI Query=" + idpSSOURI.getQuery());
        idpSSOResponseURI = processIdPLoginForm(idp, idpSSOResponseURI, idpSSOURI.getQuery(), idpLoginForm);
        LOG.debug(idp.getAuthTypeName() + " idpSSOResponseURI=" + idpSSOResponseURI);
    }
    // FIXME: ETHZ use a new PubCookie
    // PUBCOOKIE sends 200 + onload form with hidden fields to post
    else if (idpSSOResponseStatus == 200 && idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_PUBCOOKIE) {

        // parse <form> and extract hidden fields, then post
        PostMethod postPubcookieFormMethod = null;
        InputStream pubcookieFormStream = getIdpSSOMethod.getResponseBodyAsStream();
        Source source = new Source(pubcookieFormStream);
        List<Element> forms = source.findAllElements(Tag.FORM);
        for (Element form : forms) {
            String formAction = form.getAttributeValue("ACTION");
            LOG.debug("PubCookie form action=" + formAction);
            if (!idp.getAuthUrl().equalsIgnoreCase(formAction)) {
                // TODO: ERROR
                throw new RemoteException(
                        "form action: " + formAction + " doesn't match IdP authN url: " + idp.getAuthUrl());
            }
            // create PubCookie POST
            postPubcookieFormMethod = new PostMethod(formAction);

            // add all HIDDEN fields to POST
            List<FormControl> formControls = form.findFormControls();
            for (FormControl control : formControls) {
                FormControlType type = control.getFormControlType();
                if (type.equals(FormControlType.HIDDEN)) {
                    String name = control.getName();
                    Collection<String> values = control.getValues();
                    for (String value : values) {
                        LOG.debug("add hidden: " + name + "=" + value);
                        // add all hidden fields
                        postPubcookieFormMethod.addParameter(name, value);
                    }
                }
            }

        } // for all forms

        LOG.trace("getIdpSSOMethod.releaseConnection()");
        getIdpSSOMethod.releaseConnection();

        if (postPubcookieFormMethod == null) {
            // ERROR
            LOG.error("PubCookie form not found");
            throw new RemoteException("PubCookie form not found");
        }

        //
        LOG.debug("POST " + postPubcookieFormMethod.getURI());
        int postPubcookieFormStatus = executeMethod(postPubcookieFormMethod);
        LOG.debug(postPubcookieFormMethod.getStatusLine());

        // XXX
        dumpHttpClientCookies();

        // process pubcookie login form
        InputStream loginFormStream = postPubcookieFormMethod.getResponseBodyAsStream();
        idpSSOResponseURI = processIdPLoginForm(idp, idpSSOResponseURI, idpSSOURI.getQuery(), loginFormStream);
        LOG.debug("Pubcookie idpSSOResponseURI=" + idpSSOResponseURI);

        LOG.trace("postPubcookieFormMethod.releaseConnection()");
        postPubcookieFormMethod.releaseConnection();

    } else {
        // error handling
        InputStream htmlStream = getIdpSSOMethod.getResponseBodyAsStream();
        String htmlBody = inputStreamToString(htmlStream);
        LOG.error("Unexpected IdP SSO reponse: URL: " + idpSSOResponseURI + " Status: "
                + idpSSOResponseStatusLine + " AuthType: " + idp.getAuthTypeName() + " HTML:\n" + htmlBody);
        LOG.debug("getIdpSSOMethod.releaseConnection()");
        getIdpSSOMethod.releaseConnection();
        throw new RemoteException("Unexprected IdP SSO reponse: URL: " + idpSSOResponseURI + " Status: "
                + idpSSOResponseStatusLine + ". Please see the log file.");
    }

    LOG.debug("getIdpSSOMethod.releaseConnection()");
    getIdpSSOMethod.releaseConnection();

    return idpSSOResponseURI;

}

From source file:org.glite.slcs.shibclient.ShibbolethClient.java

/**
 * Parses and processes Pubcookie or CAS login form.
 * /*from  w  w  w. j ava 2s . co  m*/
 * @param idp
 * @param htmlForm
 * @throws IOException
 * @throws RemoteException
 * @throws ServiceException
 * @throws AuthException
 */
private URI processIdPLoginForm(IdentityProvider idp, URI ssoLoginURI, String ssoQuery, InputStream htmlForm)
        throws IOException, RemoteException, ServiceException, AuthException {
    LOG.info("Parse and process " + idp.getAuthTypeName() + " login form: " + ssoLoginURI);

    boolean formFound = false;
    URI idpLoginFormResponseURI = null;

    // Parse the FORM with Jericho HTML Parser
    Source source = new Source(htmlForm);
    List<Element> forms = source.findAllElements(Tag.FORM);
    for (Element form : forms) {
        String formName = form.getAttributeValue("NAME");
        // BUG FIX: UniL use a CAS login form with NO NAME defined.
        // first try with the form ID as NAME, otherwise use an empty name.
        // the metadata should also define an empty name for this particular
        // form.
        LOG.debug("form name= " + formName);
        if (formName == null) {
            LOG.warn("form have no NAME, try form ID...");
            String formId = form.getAttributeValue("ID");
            if (formId == null) {
                LOG.warn("form have no NAME and no ID, using empty name...");
                formName = "";
            } else {
                formName = formId;
            }
        }

        if (formName.equals(idp.getAuthFormName())) {
            formFound = true;
            String formAction = form.getAttributeValue("ACTION");
            LOG.debug("form action=" + formAction);
            if (formAction == null || formAction.equals("")) {
                // no form action to POST, use default from metadata
                formAction = ssoLoginURI.getEscapedURI();
                LOG.info("default form action=" + formAction);
            } else {
                URI formActionURI = new URI(formAction, false);
                if (formActionURI.isRelativeURI()) {
                    // action URL is not absolute like:
                    // http://localhost/cas/login?...
                    formActionURI = new URI(ssoLoginURI, formActionURI.getPathQuery(), true);
                }
                formAction = formActionURI.getEscapedURI();
                LOG.info("corrected form action=" + formAction);
            }

            String formMethod = form.getAttributeValue("METHOD");
            LOG.debug("form name=" + formName + " action=" + formAction + " method=" + formMethod);

            if (!formAction.equals("") && formMethod.equalsIgnoreCase("POST")) {

                PostMethod postLoginFormMethod = new PostMethod(formAction);

                // add all HIDDEN fields to POST
                List<FormControl> formControls = form.findFormControls();
                for (FormControl control : formControls) {
                    FormControlType type = control.getFormControlType();
                    if (type.equals(FormControlType.HIDDEN)) {
                        String name = control.getName();
                        Collection<String> values = control.getValues();
                        for (String value : values) {
                            LOG.debug("add hidden: " + name + "=" + value);
                            // add all hidden fields
                            postLoginFormMethod.addParameter(name, value);
                        }
                    }
                }
                // add username field
                postLoginFormMethod.addParameter(idp.getAuthFormUsername(), this.credentials_.getUserName());
                // add the PASSWORD field
                postLoginFormMethod.addParameter(idp.getAuthFormPassword(), this.credentials_.getPassword());

                // execute the login POST
                LOG.info("POST LoginFormMethod: " + postLoginFormMethod.getURI());

                int formLoginResponseStatus = executeMethod(postLoginFormMethod);
                LOG.debug(postLoginFormMethod.getStatusLine());

                // XXX
                dumpHttpClientCookies();

                // CAS, or FORM can, send a 302 + Location header back
                if (formLoginResponseStatus == 302 && (idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_CAS
                        || idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_FORM)) {
                    LOG.debug("Process " + idp.getAuthTypeName()
                            + " redirect response (302 + Location header)...");
                    Header location = postLoginFormMethod.getResponseHeader("Location");
                    if (location != null) {
                        String locationURL = location.getValue();
                        LOG.debug("302 Location: " + locationURL);
                        // CAS: if location path (/cas/login) is not the IdP
                        // 1.3
                        // SSO path (/shibboleth-idp/SSO) or the IdP 2.X
                        // /Authn/RemoteUser
                        // handler, then it's a wrong login
                        URI locationURI = new URI(locationURL, false);
                        String locationPath = locationURI.getPath();
                        String idpSSOURL = idp.getUrl();
                        URI idpSSOURI = new URI(idpSSOURL, false);
                        String idpSSOPath = idpSSOURI.getPath();
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("location path: " + locationPath);
                            LOG.debug("location is the /Authn/RemoteUser hanlder? "
                                    + locationPath.endsWith("/Authn/RemoteUser"));
                            LOG.debug("IdP SSO path: " + idpSSOPath);
                        }
                        if (!locationPath.equals(idpSSOPath) && !locationPath.endsWith("/Authn/RemoteUser")) {
                            LOG.error("Redirect response is not the SSO (" + idpSSOURL
                                    + ") or the /Authn/RemoteUser handler: " + locationURL);
                            throw new AuthException(
                                    idp.getAuthTypeName() + " Authentication failed: " + this.credentials_);
                        }
                        idpLoginFormResponseURI = new URI(locationURL, false);
                        LOG.debug("(" + idp.getAuthTypeName() + ": 302 + Location) idpLoginFormReponseURI= "
                                + idpLoginFormResponseURI);
                    } else {
                        LOG.error(idp.getAuthTypeName() + ": Status 302 but no redirect Location header");
                        throw new AuthException(
                                idp.getAuthTypeName() + " Authentication failed: " + this.credentials_);
                    }
                }
                // IdP 2.1 FORM authN send 200 and directly the SAMLResponse
                // form
                else if (formLoginResponseStatus == 200
                        && idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_FORM) {
                    // BUG FIX: check for Browser/POST hidden form element
                    // SAMLResponse for valid authentication
                    LOG.debug("check for SAMLResponse hidden element");
                    boolean samlResponseFound = false;
                    InputStream authnLoginResponse = postLoginFormMethod.getResponseBodyAsStream();
                    Source authnSource = new Source(authnLoginResponse);
                    List<Element> browserPOSTForms = authnSource.findAllElements(Tag.FORM);
                    for (Element browserPOSTForm : browserPOSTForms) {
                        List<FormControl> browserPOSTFormControls = browserPOSTForm.findFormControls();
                        for (FormControl control : browserPOSTFormControls) {
                            FormControlType type = control.getFormControlType();
                            if (type.equals(FormControlType.HIDDEN)) {
                                String name = control.getName();
                                if (name.equals("SAMLResponse")) {
                                    LOG.debug("Hidden element found: " + control.getName());
                                    samlResponseFound = true;
                                }
                            }
                        }
                    }
                    if (!samlResponseFound) {
                        LOG.error(
                                idp.getAuthTypeName() + ": no Browser/POST SAMLResponse hidden element found");
                        throw new AuthException(
                                idp.getAuthTypeName() + " Authentication failed: " + this.credentials_);

                    }

                    LOG.debug("Process FORM (200 + full Browser/POST profile) response...");
                    idpLoginFormResponseURI = new URI(idp.getUrl(), false);
                    // re-set the original SSO query params
                    idpLoginFormResponseURI.setQuery(ssoQuery);
                    LOG.debug("(FORM: 200 + Browser/POST) idpLoginFormReponseURI= " + idpLoginFormResponseURI);
                }
                // Pubcookie send 200 + fucking HTML form relay with hidden
                // fields!!!
                // <form method=post
                // action="https://aai-login.ethz.ch/PubCookie.reply"
                // name=relay>
                // then reply a redirect 302 + Location header
                else if (formLoginResponseStatus == 200
                        && idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_PUBCOOKIE) {
                    LOG.debug("Process Pubcookie (200 + relay FORM) response...");
                    InputStream pubcookieLoginResponse = postLoginFormMethod.getResponseBodyAsStream();
                    Source pubcookieSource = new Source(pubcookieLoginResponse);
                    PostMethod postPubcookieRelayMethod = null;
                    List<Element> relayForms = pubcookieSource.findAllElements(Tag.FORM);
                    for (Element relayForm : relayForms) {
                        String relayFormAction = relayForm.getAttributeValue("ACTION");
                        LOG.debug("Pubcookie relay form action= " + relayFormAction);
                        if (relayFormAction == null) {
                            LOG.error("Pubcookie relay form action not found.");
                            throw new RemoteException("Pubcookie relay form action not found");
                        }
                        // create PubCookie relay POST
                        postPubcookieRelayMethod = new PostMethod(relayFormAction);

                        // add all HIDDEN fields to POST
                        List<FormControl> relayFormControls = relayForm.findFormControls();
                        for (FormControl control : relayFormControls) {
                            FormControlType type = control.getFormControlType();
                            if (type.equals(FormControlType.HIDDEN)) {
                                String name = control.getName();
                                Collection<String> values = control.getValues();
                                for (String value : values) {
                                    LOG.debug("add hidden: " + name + "=" + value);
                                    // add all hidden fields
                                    postPubcookieRelayMethod.addParameter(name, value);
                                }
                            }
                        } // add hidden fields
                    } // for all relay forms

                    if (postPubcookieRelayMethod != null) {
                        LOG.debug("POST postPubcookieRelayMethod: " + postPubcookieRelayMethod.getURI());
                        int pubcookieRelayStatus = executeMethod(postPubcookieRelayMethod);
                        LOG.debug(postPubcookieRelayMethod.getStatusLine());
                        Header location = postPubcookieRelayMethod.getResponseHeader("Location");
                        LOG.debug("postPubcookieRelayMethod.releaseConnection()");
                        postPubcookieRelayMethod.releaseConnection();
                        if (location != null) {
                            String locationURL = location.getValue();
                            LOG.debug("302 Location: " + locationURL);
                            // parse Location
                            idpLoginFormResponseURI = new URI(locationURL, false);
                            LOG.debug("(PubCookie: 302 + Location header) idpLoginFormReponseURI= "
                                    + idpLoginFormResponseURI);
                        } else {
                            LOG.error("Pubcookie relay response 302 + Location header not found");
                            throw new AuthException(
                                    idp.getAuthTypeName() + " Authentication failed: " + this.credentials_);
                        }
                    } else {
                        LOG.error("Pubcookie relay form not found");
                        throw new AuthException(
                                idp.getAuthTypeName() + " Authentication failed: " + this.credentials_);
                    }

                    // XXX
                    dumpHttpClientCookies();
                } else {
                    LOG.error("Unexpected response status: " + formLoginResponseStatus + " AuthType:"
                            + idp.getAuthTypeName());
                    throw new AuthException(
                            idp.getAuthTypeName() + " Authentication failed: " + this.credentials_);
                }

                LOG.debug("POSTLoginFormMethod.releaseConnection()");
                postLoginFormMethod.releaseConnection();

            } // end if form action is set and method is POST
        } // end if form name match metadata
    } // end for all forms

    if (!formFound) {
        LOG.error("FORM name=" + idp.getAuthFormName() + " not found");
        throw new ServiceException("FORM name=" + idp.getAuthFormName() + " not found");
    }

    return idpLoginFormResponseURI;

}

From source file:org.glite.slcs.shibclient.TestShibbolethClient.java

/**
 * @param args//w ww.  ja  va2 s. c  o  m
 * @throws MalformedURLException
 */
public static void main(String[] args) throws Exception {

    // create credentials
    // XXX WARNING PASSWORD IN SOURCE CODE
    final String idpProviderID = "vho-switchaai.ch";
    final String username = "test-tschopp";
    final String password = "XXXXXXXXXXXX";
    ShibbolethCredentials credentials = new ShibbolethCredentials(username, password, idpProviderID);
    // create metadata
    final String filename = "slcs-init.xml";
    ShibbolethClientMetadata metadata = new ShibbolethClientMetadata(filename);

    // create httpclient
    String truststore = "truststore.switchaai.jks";
    ExtendedProtocolSocketFactory protocolSocketFactory = new ExtendedProtocolSocketFactory(truststore);
    Protocol https = new Protocol("https", protocolSocketFactory, 443);
    Protocol.registerProtocol("https", https);
    HttpClient httpClient = new HttpClient();
    setHttpClientUserAgent(httpClient);

    // create shib client
    ShibbolethClient client = new ShibbolethClient(httpClient, metadata, credentials);

    // SLCS login and certificate URLs
    String slcsHost = "https://slcs.switch.ch";
    String slcsLoginURL = slcsHost + "/SLCS/login";
    String slcsCertificateURL = slcsHost + "/SLCS/certificate";

    // shib login
    System.out.println("Authenticate with " + credentials);
    client.authenticate(slcsLoginURL);

    // SLCS login
    System.out.println("GET login: " + slcsLoginURL);
    GetMethod GETLogin = new GetMethod(slcsLoginURL);
    client.executeMethod(GETLogin);
    System.out.println(GETLogin.getStatusLine());
    // check status

    // read response
    InputStream is = GETLogin.getResponseBodyAsStream();
    StringBuffer loginResponse = getContent(is);
    GETLogin.releaseConnection();

    System.out.println(loginResponse);

    System.exit(1);

    // parse response
    String dn = getDN(loginResponse);
    // System.out.println("DN=" + dn);
    String authToken = getAuthorizationToken(loginResponse);
    // System.out.println("AuthorizationToken=" + authToken);
    // TODO checks null

    // create key pair
    System.out.println("create and store keys...");
    char[] pass = password.toCharArray();
    CertificateKeys keys = new CertificateKeys(2048, pass);
    keys.storePEMPrivate("/var/tmp/" + username + "key.pem");
    // create csr
    System.out.println("create and store csr...");
    CertificateRequest csr = new CertificateRequest(keys, dn);
    csr.storePEM("/var/tmp/" + username + "cert_req.pem");
    // post csr
    PostMethod POSTCertificateRequestMethod = new PostMethod(slcsCertificateURL);
    POSTCertificateRequestMethod.addParameter("AuthorizationToken", authToken);
    POSTCertificateRequestMethod.addParameter("CertificateSigningRequest", csr.getPEMEncoded());
    System.out.println("POST: " + slcsCertificateURL);
    client.executeMethod(POSTCertificateRequestMethod);
    System.out.println(POSTCertificateRequestMethod.getStatusLine());
    // check status

    // parse and check response
    StringBuffer certificateResponse = getContent(POSTCertificateRequestMethod.getResponseBodyAsStream());
    POSTCertificateRequestMethod.releaseConnection();
    System.out.println(certificateResponse);

    // get certificate
    String pemCert = getCertificate(certificateResponse);
    // System.out.println("Certificate=" + pemCert);

    // parse and store certificate (with chain)
    System.out.println("parse and store cert...");
    StringReader reader = new StringReader(pemCert);
    Certificate cert = Certificate.readPEM(reader);
    cert.storePEM("/var/tmp/" + username + "cert.pem");

    System.out.println();
    System.out.println("openssl x509 -text -noout -in /var/tmp/" + username + "cert.pem");

}

From source file:org.glite.slcs.SLCSInit.java

public void slcsCertificateRequest() throws SLCSException {
    PostMethod postCertificateRequestMethod = new PostMethod(certificateRequestUrl_);
    postCertificateRequestMethod.addParameter("AuthorizationToken", authorizationToken_);
    postCertificateRequestMethod.addParameter("CertificateSigningRequest", certificateRequest_.getPEMEncoded());
    try {//from w  w  w. j  a  va  2 s. co m
        LOG.info("POST CSR: " + certificateRequestUrl_);
        int status = shibClient_.executeMethod(postCertificateRequestMethod);
        LOG.debug(postCertificateRequestMethod.getStatusLine());
        // check status
        if (status != 200) {
            LOG.error("SLCS certificate request failed: " + postCertificateRequestMethod.getStatusLine());
            throw new ServiceException(
                    "SLCS certificate request failed: " + postCertificateRequestMethod.getStatusLine());
        }
        // read response
        InputStream is = postCertificateRequestMethod.getResponseBodyAsStream();
        Source source = new Source(is);
        checkSLCSResponse(source, "SLCSCertificateResponse");
        parseSLCSCertificateResponse(source);

    } catch (IOException e) {
        LOG.error("Failed to request the certificate", e);
        throw new SLCSException("Failed to request the certificate", e);
    } finally {
        postCertificateRequestMethod.releaseConnection();
    }
}

From source file:org.intermine.webservice.client.util.HttpConnection.java

private void setPostMethodParameters(PostMethod postMethod, Map<String, List<String>> parameterMap) {
    for (String name : parameterMap.keySet()) {
        for (String value : parameterMap.get(name)) {
            postMethod.addParameter(name, value);
        }//from   www . j av a  2s.  co m
    }
}

From source file:org.jahia.ajax.gwt.helper.PublicationHelper.java

public void validateConnection(Map<String, String> props, JCRSessionWrapper jcrSession, Locale uiLocale)
        throws GWTJahiaServiceException {
    PostMethod post = null;
    URL url = null;//from   ww w  .j a  v a 2  s. c o m
    try {
        String languageCode = jcrSession.getNodeByIdentifier(props.get("node")).getResolveSite()
                .getDefaultLanguage();
        String theUrl = props.get("remoteUrl") + Render.getRenderServletPath() + "/live/" + languageCode
                + props.get("remotePath") + ".preparereplay.do";
        url = new URL(theUrl);
        post = new PostMethod(theUrl);
        post.addParameter("testOnly", "true");
        post.addRequestHeader("accept", "application/json");
        HttpState state = new HttpState();
        state.setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(props.get("remoteUser"), props.get("remotePassword")));
        HttpClient httpClient = httpClientService.getHttpClient(theUrl);
        Credentials proxyCredentials = httpClient.getState().getProxyCredentials(AuthScope.ANY);
        if (proxyCredentials != null) {
            state.setProxyCredentials(AuthScope.ANY, proxyCredentials);
        }
        if (httpClient.executeMethod(null, post, state) != 200) {
            logger.warn("Connection to URL: {} failed with status {}", url, post.getStatusLine());
            throw new GWTJahiaServiceException(Messages.getInternalWithArguments(
                    "label.gwt.error.connection.failed.with.the.status", uiLocale, post.getStatusLine()));
        }
    } catch (RepositoryException e) {
        logger.error("Unable to get source node with identifier: " + props.get("node") + ". Cause: "
                + e.getMessage(), e);
        throw new GWTJahiaServiceException(Messages.getInternalWithArguments(
                "label.gwt.error.connection.failed.with.the.an.error", uiLocale, e.getMessage()));
    } catch (HttpException e) {
        logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e);
        throw new GWTJahiaServiceException(Messages.getInternalWithArguments(
                "label.gwt.error.connection.failed.with.the.an.error", uiLocale, e.getMessage()));
    } catch (IOException e) {
        logger.error("Unable to get the content of the URL: " + url + ". Cause: " + e.getMessage(), e);
        throw new GWTJahiaServiceException(Messages.getInternalWithArguments(
                "label.gwt.error.connection.failed.with.the.an.error", uiLocale, e.getMessage()));
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.jahia.bin.FindPrincipalTest.java

@Before
public void setUp() throws Exception {

    // Create an instance of HttpClient.
    client = new HttpClient();

    // todo we should really insert content to test the find.

    PostMethod loginMethod = new PostMethod(getLoginServletURL());
    loginMethod.addParameter("username", "root");
    loginMethod.addParameter("password", "root1234");
    loginMethod.addParameter("redirectActive", "false");
    // the next parameter is required to properly activate the valve check.
    loginMethod.addParameter(LoginEngineAuthValveImpl.LOGIN_TAG_PARAMETER, "1");

    int statusCode = client.executeMethod(loginMethod);
    if (statusCode != HttpStatus.SC_OK) {
        logger.error("Method failed: " + loginMethod.getStatusLine());
    }/*from   www  . j a  va2 s .co m*/
}