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

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

Introduction

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

Prototype

public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException 

Source Link

Usage

From source file:org.iavante.sling.searcher.SearcherServiceTestIT.java

@org.junit.BeforeClass
static public void initialize() {
    try {//from  ww  w  .j a  v a2s. c om
        Thread.sleep(3000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    /* get env params */
    Map<String, String> envs = System.getenv();
    Set<String> keys = envs.keySet();

    Iterator<String> it = keys.iterator();
    boolean hashost = false;
    while (it.hasNext()) {
        String key = (String) it.next();
        if (key.compareToIgnoreCase(HOSTVAR) == 0) {
            SLING_URL = SLING_URL + (String) envs.get(key);
            hashost = true;
            break;
        }
    }
    if (hashost == false)
        SLING_URL = SLING_URL + HOSTPREDEF;

    /* make http connection */
    client = new HttpClient();
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    defaultcreds = new UsernamePasswordCredentials("admin", "admin");
    PostMethod post_create_col;

    /* tests if the collection exists */
    GetMethod get_create_col = new GetMethod(SLING_URL + COLLECTIONS_URL + "/" + COLLECTION);

    get_create_col.setDoAuthentication(true);

    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    try {
        client.executeMethod(get_create_col);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    if (get_create_col.getStatusCode() != 404) {
        deletecontent();
    }

    /* create a collection */
    post_create_col = new PostMethod(SLING_URL + COLLECTIONS_URL + "/*");

    post_create_col.setDoAuthentication(true);

    NameValuePair[] data_create_col = { new NameValuePair("sling:resourceType", "gad/collection"),
            new NameValuePair("title", COLLECTION), new NameValuePair("subtitle", ""),
            new NameValuePair("schema", SCHEMA), new NameValuePair("jcr:created", ""),
            new NameValuePair("jcr:createdBy", ""), new NameValuePair("jcr:lastModified", ""),
            new NameValuePair("jcr:lastModifiedBy", "") };
    post_create_col.setRequestBody(data_create_col);
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    try {
        client.executeMethod(post_create_col);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    assertEquals("Creando la coleccion", 201, post_create_col.getStatusCode());
    post_create_col.releaseConnection();
    // collection created
    // Get the content
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
    /* create a content */
    post_create_col = new PostMethod(SLING_URL + COLLECTIONS_URL + "/" + COLLECTION + "/contents/*");

    post_create_col.setDoAuthentication(true);

    NameValuePair[] data_create_col_content = { new NameValuePair("sling:resourceType", "gad/content"),
            new NameValuePair("title", TITLE_CONTENT), new NameValuePair("author", "test_autor@tests.com"),
            new NameValuePair("schema", SCHEMA), new NameValuePair("description", DESCRIPTION),
            new NameValuePair("origin", "final cut"), new NameValuePair("lang", "es"),
            new NameValuePair("tags", "recetas equilibradas"), new NameValuePair("tags@TypeHint", "String[]"),
            new NameValuePair("jcr:created", ""), new NameValuePair("jcr:createdBy", ""),
            new NameValuePair("jcr:lastModified", ""), new NameValuePair("jcr:lastModifiedBy", "") };
    post_create_col.setRequestBody(data_create_col_content);
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    try {

        client.executeMethod(post_create_col);

    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    assertEquals("Creando contenido", 201, post_create_col.getStatusCode());
    post_create_col.releaseConnection();
    // Content created
    // Get the content
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    /* create a source */
    post_create_col = new PostMethod(
            SLING_URL + COLLECTIONS_URL + "/" + COLLECTION + "/contents/tests_search_title/sources/*");

    post_create_col.setDoAuthentication(true);

    NameValuePair[] data_create_col_source = { new NameValuePair("sling:resourceType", "gad/source"),
            new NameValuePair("title", SOURCE_TITLE), new NameValuePair("author", "test_autor@tests.com"),
            new NameValuePair("schema", SCHEMA), new NameValuePair("description", DESCRIPTION),
            new NameValuePair("jcr:created", ""), new NameValuePair("jcr:createdBy", ""),
            new NameValuePair("jcr:lastModified", ""), new NameValuePair("jcr:lastModifiedBy", "") };
    post_create_col.setRequestBody(data_create_col_source);
    // post.setDoAuthentication(true);
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    try {

        client.executeMethod(post_create_col);

    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    // Get the content

    assertEquals("Creando fuente", 201, post_create_col.getStatusCode());
    post_create_col.releaseConnection();
    // Source created

    /* send to review */
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }
    post_create_col = new PostMethod(
            SLING_URL + COLLECTIONS_URL + "/" + COLLECTION + "/contents/" + TITLE_CONTENT);

    post_create_col.setDoAuthentication(true);

    NameValuePair[] data_send_review = { new NameValuePair(":operation", "copy"),
            new NameValuePair(":dest", "/content/catalogo/pendientes/"), new NameValuePair("replace", "true") };
    post_create_col.setRequestBody(data_send_review);
    // post.setDoAuthentication(true);
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    try {

        client.executeMethod(post_create_col);

    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    // test if sent

    assertEquals("Mandando a revision", 201, post_create_col.getStatusCode());
    post_create_col.releaseConnection();
    // send to review finished

}

From source file:org.iavante.sling.searcher.SearcherServiceTestIT.java

@org.junit.AfterClass
static public void deletecontent() {
    try {/*  w w  w  . j  av  a 2  s .c  o  m*/
        Thread.sleep(3000);
    } catch (InterruptedException e1) {

        e1.printStackTrace();
    }

    /* delete collection */
    PostMethod post_create_col = new PostMethod(SLING_URL + COLLECTIONS_URL + "/" + COLLECTION);

    post_create_col.setDoAuthentication(true);

    NameValuePair[] data_create_col = { new NameValuePair(":operation", "delete"), };
    post_create_col.setRequestBody(data_create_col);

    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    try {

        client.executeMethod(post_create_col);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    assertEquals("Deleting content", 200, post_create_col.getStatusCode());
    post_create_col.releaseConnection();
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

}

From source file:org.iavante.sling.transcodingServer.impl.TranscodingManagerImpl.java

@SuppressWarnings("unchecked")
private String notificateTransformation(Node jobNode) {
    log.info("notificateTransformation: reading properties");
    String response = "";
    String source_location = "";
    String target_location = "";

    String notification_url = null;
    String gadUser = null;/*w w w.  j  a  v a  2  s . c om*/
    String gadPassword = null;
    String source_file = null;
    String target_file = null;

    HttpClient client = null;
    List authPrefs = new ArrayList(2);
    client = new HttpClient();
    Credentials defaultcreds;
    // first of all. We have to take the useful data
    try {
        // source_location-->sourcefile
        // target_location-->targetfile
        // ds_custom_props-->ds_custom_props
        source_location = jobNode.getProperty("source_location").getValue().getString();
        String[] splitedSourceLocation = source_location.split("/");
        source_file = splitedSourceLocation[splitedSourceLocation.length - 1];

        target_location = jobNode.getProperty("target_location").getValue().getString();
        String[] splitedTargetLocation = target_location.split("/");
        target_file = splitedTargetLocation[splitedTargetLocation.length - 1];

        notification_url = jobNode.getProperty("notification_url").getValue().getString();

        gadUser = Constantes.getGADuser();
        gadPassword = Constantes.getGADpassword();

        log.info("notificateTransformation: notification_url:" + notification_url);
        log.info("notificateTransformation: target_file:" + target_file);
        log.info("notificateTransformation: source_file:" + source_file);

    } catch (ValueFormatException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (PathNotFoundException e) {
        e.printStackTrace();
    } catch (RepositoryException e) {
        e.printStackTrace();
    }
    // Using the hhtp client. This has to be authenticated
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    defaultcreds = new UsernamePasswordCredentials(gadUser, gadPassword);
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    // Using the POST Method
    PostMethod post_notification = new PostMethod(notification_url);
    post_notification.setDoAuthentication(true);
    NameValuePair[] data_notification = { new NameValuePair("sling:resourceType", "gad/transformation"),
            new NameValuePair("title", source_file),
            //
            new NameValuePair("file", target_file), new NameValuePair("jcr:lastModified", "") };
    post_notification.setRequestBody(data_notification);
    post_notification.setDoAuthentication(true);
    try {
        log.info("notificateTransformation: Notificating...");
        client.executeMethod(post_notification);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    // Response in Status
    int status = post_notification.getStatusCode();
    post_notification.releaseConnection();
    if (status == 200) {
        response = "OK. Notificated. Status =" + status;
        log.info(response);
    } else {
        response = "Error notificating. Status =" + status;
        log.error(response);
    }
    return response;
}

From source file:org.iavante.sling.transcodingServer.impl.TranscodingManagerImpl.java

@SuppressWarnings("unchecked")
private String notificateStatus(String mystatus, Node jobNode) {
    log.info("notificatingStatus: reading properties");
    String response = "";

    String notification_url = null;
    String gadUser = null;/*from w w w.  j ava 2s .c  o  m*/
    String gadPassword = null;

    HttpClient client = null;
    List authPrefs = new ArrayList(2);
    client = new HttpClient();
    Credentials defaultcreds;
    // first of all. We have to take the useful data
    try {

        notification_url = jobNode.getProperty("notification_url").getValue().getString();

        gadUser = Constantes.getGADuser();
        gadPassword = Constantes.getGADpassword();

    } catch (ValueFormatException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (PathNotFoundException e) {
        e.printStackTrace();
    } catch (RepositoryException e) {
        e.printStackTrace();
    }
    // Using the hhtp client. This has to be authenticated
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    defaultcreds = new UsernamePasswordCredentials(gadUser, gadPassword);
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    // Using the POST Method
    PostMethod post_notification = new PostMethod(notification_url);
    post_notification.setDoAuthentication(true);
    NameValuePair[] data_notification = { new NameValuePair("sling:resourceType", "gad/transformation"),
            new NameValuePair("state", mystatus) };
    post_notification.setRequestBody(data_notification);
    post_notification.setDoAuthentication(true);
    try {
        log.info("notificatingStatus...");
        client.executeMethod(post_notification);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    // Response in Status
    int status = post_notification.getStatusCode();
    post_notification.releaseConnection();
    if (status == 200) {
        response = "OK. Notificated. Status =" + status;
        log.info(response);
    } else {
        response = "Error notificating. Status =" + status;
        log.error(response);
    }
    return response;
}

From source file:org.iavante.sling.transcodingServer.TranscodingServerTestIT.java

protected void setUp() {

    Map<String, String> envs = System.getenv();
    Set<String> keys = envs.keySet();

    Iterator<String> it = keys.iterator();
    boolean hashost = false;
    while (it.hasNext()) {
        String key = (String) it.next();

        if (key.compareTo(HOSTVAR) == 0) {
            SLING_URL = SLING_URL + (String) envs.get(key);
            hashost = true;//ww w.  j  a  va 2  s  .  c  o  m
        }
    }

    if (hashost == false)
        SLING_URL = SLING_URL + HOSTPREDEF;

    client = new HttpClient();

    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    defaultcreds = new UsernamePasswordCredentials("admin", "admin");

    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    // Create a wrong job

    PostMethod post_create_job = new PostMethod(SLING_URL + JOBS_PENDING_URL);

    post_create_job.setDoAuthentication(true);

    NameValuePair[] data_create_job = { new NameValuePair("sling:resourceType", resourceType),
            new NameValuePair("source_location", wrong_source_location),
            new NameValuePair("target_location", wrong_target_location),
            new NameValuePair("executable", executable), new NameValuePair("title", title),
            new NameValuePair("notification_url", notification_url),
            new NameValuePair("extern_storage_server", extern_storage_server),
            new NameValuePair("extern_storage_url", extern_storage_url), new NameValuePair("jcr:created", ""),
            new NameValuePair("jcr:createdBy", ""), new NameValuePair("jcr:lastModified", ""),
            new NameValuePair("jcr:lastModifiedBy", "") };

    post_create_job.setRequestBody(data_create_job);

    try {
        client.executeMethod(post_create_job);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    post_create_job.releaseConnection();

}

From source file:org.iavante.sling.transcodingServer.TranscodingServerTestIT.java

protected void tearDown() {

    // Delete the content
    try {/*from   w ww  . j a  v  a 2  s .  c  o  m*/
        Thread.sleep(4000);
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    PostMethod post_delete = new PostMethod(SLING_URL + JOBS_ERROR_URL + title);
    NameValuePair[] data_delete = { new NameValuePair(":operation", "delete"), };

    post_delete.setDoAuthentication(true);
    post_delete.setRequestBody(data_delete);

    try {
        client.executeMethod(post_delete);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    assertEquals(post_delete.getStatusCode(), 200);
    // System.out.println("Response: " + post_delete.getStatusCode());
    post_delete.releaseConnection();
}

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

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

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

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

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

        pMethod.setQueryString(queryString);

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

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

From source file:org.jabox.cis.hudson.HudsonConnector.java

/**
 * Implementation inspired by groovy code here:
 * http://wiki.hudson-ci.org/display/HUDSON/Authenticating+scripted+clients
 *///w  w  w.j  a  va2  s.com
public boolean addProject(final Project project, final CISConnectorConfig dc) throws IOException, SAXException {
    HudsonConnectorConfig hcc = (HudsonConnectorConfig) dc;
    String url = dc.getServer().getUrl();

    HttpClient client = new HttpClient();
    client.getState().setCredentials(null, null,
            new UsernamePasswordCredentials(hcc.getUsername(), hcc.getPassword()));

    // Hudson does not do any authentication negotiation,
    // ie. it does not return a 401 (Unauthorized)
    // but immediately a 403 (Forbidden)
    client.getState().setAuthenticationPreemptive(true);

    String uri = url + "createItem?name=" + project.getName();
    PostMethod post = new PostMethod(uri);
    post.setDoAuthentication(true);

    post.setRequestHeader("Content-type", "text/xml; charset=UTF-8");

    InputStream is = getConfigXMLStream(project);

    String body = parseInputStream(is, project);
    post.setRequestBody(body);
    try {
        int result = client.executeMethod(post);
        LOGGER.info("Return code: " + result);
        for (Header header : post.getResponseHeaders()) {
            LOGGER.info(header.toString().trim());
        }
        LOGGER.info(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }

    // Trigger the Hudson build
    PostMethod triggerBuild = new PostMethod(url + "/job/" + project.getName() + "/build");
    client.executeMethod(triggerBuild);
    return true;
}

From source file:org.jabox.cis.jenkins.JenkinsConnector.java

/**
 * Implementation inspired by groovy code here:
 * http://wiki.jenkins-ci.org/display/*w  ww. ja  v  a  2  s  .com*/
 * /JENKINS/Authenticating+scripted+clients
 */
public boolean addProject(final Project project, final CISConnectorConfig dc) throws IOException, SAXException {
    JenkinsConnectorConfig hcc = (JenkinsConnectorConfig) dc;
    String url = dc.getServer().getUrl();

    HttpClient client = new HttpClient();
    client.getState().setCredentials(null, null,
            new UsernamePasswordCredentials(hcc.getUsername(), hcc.getPassword()));

    // Jenkins does not do any authentication negotiation,
    // ie. it does not return a 401 (Unauthorized)
    // but immediately a 403 (Forbidden)
    client.getState().setAuthenticationPreemptive(true);

    String uri = url + "createItem?name=" + project.getName();
    PostMethod post = new PostMethod(uri);
    post.setDoAuthentication(true);

    post.setRequestHeader("Content-type", "text/xml; charset=UTF-8");

    InputStream is = getConfigXMLStream(project);

    String body = parseInputStream(is, project);
    post.setRequestBody(body);
    try {
        int result = client.executeMethod(post);
        LOGGER.info("Return code: " + result);
        for (Header header : post.getResponseHeaders()) {
            LOGGER.info(header.toString().trim());
        }
        LOGGER.info(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }

    // Trigger the Jenkins build
    PostMethod triggerBuild = new PostMethod(url + "/job/" + project.getName() + "/build");
    client.executeMethod(triggerBuild);
    return true;
}

From source file:org.jboss.test.security.test.SubjectContextUnitTestCase.java

public void testUnprotectedEjbMethodViaServlet() throws Exception {
    log.debug("+++ testUnprotectedEjbMethodViaServlet()");
    SecurityAssociation.clear();/* w  w  w .ja v a 2  s  . c  o  m*/

    Principal callerIdentity = new SimplePrincipal("guest");
    Principal runAsIdentity = new SimplePrincipal("runAsUser");
    HashSet expectedCallerRoles = new HashSet();
    HashSet expectedRunAsRoles = new HashSet();
    expectedRunAsRoles.add("identitySubstitutionCaller");
    expectedRunAsRoles.add("extraRunAsRole");
    CallerInfo info = new CallerInfo(callerIdentity, runAsIdentity, expectedCallerRoles, expectedRunAsRoles);

    String baseURLNoAuth = HttpUtils.getBaseURLNoAuth();
    PostMethod formPost = new PostMethod(baseURLNoAuth + "subject-context/unrestricted/RunAsServlet");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject("unprotectedEjbMethod");
    oos.writeObject(info);
    oos.close();
    log.info("post content length: " + baos.toByteArray().length);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    formPost.setRequestBody(bais);
    HttpClient httpConn = new HttpClient();
    int responseCode = httpConn.executeMethod(formPost);
    assertTrue("POST OK(" + responseCode + ")", responseCode == HttpURLConnection.HTTP_OK);
}