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

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

Introduction

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

Prototype

public PostMethod(String paramString) 

Source Link

Usage

From source file:com.ibm.hrl.proton.adapters.rest.client.RestClient.java

/**
 * Put the specified event instance to the specified consumer.
 * The consumer is specified by the URL (which includes all the relevant info - the web
 * server name, port name, web service name and the URI path 
 * The content type can be either application/xml,application/json or plain text
 * The content type will be specified by the specific consumer, and a formatter
 * will be supplied to format the event instance to that type
 * //  w  w w. jav a 2 s.c  o  m
 * @param url
 * @return
 * @throws AdapterException 
 * @throws RESTException 
 */
protected static void putEventToConsumer(String url, String eventInstance, String contentType, String authToken)
        throws RESTException {
    // Prepare HTTP PUT
    PostMethod postMethod = new PostMethod(url);

    if (eventInstance != null) {

        RequestEntity requestEntity = new ByteArrayRequestEntity(eventInstance.getBytes());
        postMethod.setRequestEntity(requestEntity);

        // Specify content type and encoding
        // If content encoding is not explicitly specified
        // ISO-8859-1 is assumed
        // postMethod.setRequestHeader("Content-Type", contentType+"; charset=ISO-8859-1");
        postMethod.setRequestHeader("Content-Type", contentType);

        if (null != authToken && !authToken.isEmpty()) {
            postMethod.setRequestHeader("X-Auth-Token", authToken);
        }

        // Get HTTP client
        HttpClient httpclient = new HttpClient();

        // Execute request
        try {

            int result = httpclient.executeMethod(postMethod);

            if (result < 200 || result >= 300) {
                Header[] reqHeaders = postMethod.getRequestHeaders();
                StringBuffer headers = new StringBuffer();
                for (int i = 0; i < reqHeaders.length; i++) {
                    headers.append(reqHeaders[i].toString());
                    headers.append("\n");
                }
                throw new RESTException("Could not perform POST of event instance: \n" + eventInstance
                        + "\nwith request headers:\n" + headers + "to consumer " + url + ", responce result: "
                        + result);
            }

        } catch (Exception e) {
            throw new RESTException(e);
        } finally {
            // Release current connection to the connection pool 
            // once you are done
            postMethod.releaseConnection();
        }
    } else {
        System.out.println("Invalid request");
    }
    //        PutMethod putMethod = new PutMethod(url);        
    // 
    //        if(eventInstance != null) {
    //           RequestEntity requestEntity = new ByteArrayRequestEntity(eventInstance.getBytes());
    //           putMethod.setRequestEntity(requestEntity);
    //
    //        
    //           // Specify content type and encoding
    //           // If content encoding is not explicitly specified
    //           // ISO-8859-1 is assumed
    //           putMethod.setRequestHeader(
    //                   "Content-type", contentType+"; charset=ISO-8859-1");
    //           
    //           // Get HTTP client
    //           HttpClient httpclient = new HttpClient();
    //           
    //           // Execute request
    //           try {
    //               
    //               int result = httpclient.executeMethod(putMethod);
    //                              
    //               if (result < 200 || result >= 300)
    //               {
    //                  throw new RESTException("Could not perform PUT of event instance "+eventInstance+" to consumer "+ url+", responce result: "+result);
    //               }
    //              
    //           } catch(Exception e)
    //           {
    //              throw new RESTException(e);
    //           }
    //           finally {
    //               // Release current connection to the connection pool 
    //               // once you are done
    //               putMethod.releaseConnection();
    //           }
    //        } else
    //        {
    //           System.out.println ("Invalid request");
    //        }

}

From source file:com.ephesoft.dcma.util.WebServiceCaller.java

/**
 * Api to simply hit webservice. It will return true or false if Webservice hit was successful or unsuccessful respectively
 * /*from   w w  w  .  ja  va 2s .c o m*/
 * @param serviceURL
 * @return
 */
private static boolean hitWebservice(final String serviceURL) {
    LOGGER.debug("Giving a hit at webservice URL.");
    boolean isActive = false;
    if (!EphesoftStringUtil.isNullOrEmpty(serviceURL)) {

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

        // Create a method instance.
        PostMethod method = new PostMethod(serviceURL);

        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode == HttpStatus.SC_OK) {
                isActive = true;
            } else {
                LOGGER.info(EphesoftStringUtil.concatenate("Execute Method failed: ", method.getStatusLine()));
            }
        } catch (HttpException httpException) {
            LOGGER.error(
                    EphesoftStringUtil.concatenate("Fatal protocol violation: ", httpException.getMessage()));
        } catch (IOException ioException) {
            LOGGER.error(EphesoftStringUtil.concatenate("Fatal transport error: ", ioException.getMessage()));
        } finally {
            // Release the connection.
            if (method != null) {
                method.releaseConnection();
            }
        }
    }
    return isActive;
}

From source file:com.boundary.sdk.event.notification.WebhookRouteBuilderTest.java

@Test
public void testNotification() throws InterruptedException, IOException {
    String body = readFile(NOTIFICATION_JSON, Charset.defaultCharset());

    out.setExpectedMessageCount(1);/* ww  w. ja v  a  2 s.  c om*/

    // Get the url from the sprint DSL file by
    // 1) Getting the context
    // 2) Getting the registry
    // 3) Lookup the bean
    // 4) Call method to get url
    // 5) Strip out component name, "jetty:"
    CamelContext context = out.getCamelContext();
    Registry registry = context.getRegistry();
    WebHookRouteBuilder builder = (WebHookRouteBuilder) registry.lookupByName("webhook-route-builder");
    assertNotNull("builder is null", builder);
    String url = null;
    url = builder.getFromUri();
    url = url.replaceFirst("jetty:", "");
    LOG.debug("url {}", url);

    // Send an HTTP request with the JSON paylod that is sent
    // from a Boundary Event Notification
    HttpClient httpclient = new HttpClient();
    PostMethod httppost = new PostMethod(url);
    Header contentHeader = new Header("Content-Type", "application/json");
    httppost.setRequestHeader(contentHeader);
    StringRequestEntity reqEntity = new StringRequestEntity(body, null, null);
    httppost.setRequestEntity(reqEntity);

    // Check our reponse status
    int status = httpclient.executeMethod(httppost);
    assertEquals("Received wrong response status", 200, status);

    // Assert the mock end point
    out.assertIsSatisfied();

    // Get
    List<Exchange> exchanges = out.getExchanges();
    LOG.debug("EXCHANGE COUNT: " + exchanges.size());
    for (Exchange exchange : exchanges) {
        Message message = exchange.getIn();
        Object o = message.getBody();
        LOG.debug("class: " + o.getClass().toString());
        Notification notif = message.getBody(Notification.class);
        validateNotification(notif);
    }
}

From source file:com.shelrick.openamplify.client.OpenAmplifyClientImpl.java

@Override
public OpenAmplifyResponse analyzeText(String inputText, Analysis analysis, Integer maxTopicResults)
        throws OpenAmplifyClientException {
    List<NameValuePair> params = getBaseParams();
    inputText = inputText.replaceAll("'@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@'", " ");
    params.add(new NameValuePair("inputtext", inputText));
    params.add(new NameValuePair("analysis", analysis.type()));
    params.add(new NameValuePair("maxtopicresult", maxTopicResults.toString()));

    PostMethod postMethod = new PostMethod(apiUrl);
    postMethod.addParameters(params.toArray(new NameValuePair[1]));

    String responseText = doRequest(postMethod);
    //System.out.println(responseText);
    return parseResponse(responseText, analysis);
}

From source file:es.carebear.rightmanagement.client.RestClient.java

public void deleteTest(String authName, String target) throws IOException {
    HttpClient client = new HttpClient();

    PostMethod deleteMethod = new PostMethod(getServiceBaseURI() + "/client/users/delete/" + target);

    deleteMethod.addParameter("authName", "Admin");

    int responseCode = client.executeMethod(deleteMethod);

    System.out.println(responseCode);
}

From source file:com.predic8.membrane.integration.Http10Test.java

@Test
public void testMultiplePost() throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);

    PostMethod post = new PostMethod("http://localhost:3000/axis2/services/BLZService");
    InputStream stream = this.getClass().getResourceAsStream("/getBank.xml");

    InputStreamRequestEntity entity = new InputStreamRequestEntity(stream);
    post.setRequestEntity(entity);//  w w  w.  j a v  a2s  .c  o m
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "\"\"");

    for (int i = 0; i < 100; i++) {
        //System.out.println("Iteration: " + i);
        int status = client.executeMethod(post);
        assertEquals(200, status);
        String response = post.getResponseBodyAsString();
        assertNotNull(response);
        assertTrue(response.length() > 0);
    }

}

From source file:ch.ksfx.web.services.spidering.http.HttpClientHelper.java

/**
 * Returns an executed PostMethod object with the given URL
 *
 * @param url URL for HTTP POST request/*from w w w  . j  ava2s.  co  m*/
 * @return executed PostMethod object
 */
public PostMethod executePostMethod(String url) {
    try {
        url = encodeURL(url);
        PostMethod postMethod = new PostMethod(url);
        postMethod.setFollowRedirects(true);
        postMethod = (PostMethod) executeMethod(postMethod);
        return postMethod;
    } catch (Exception e) {
        logger.severe("Error while generating POST method: " + e);
        return null;
    }
}

From source file:edu.unc.lib.dl.admin.controller.RESTProxyController.java

@RequestMapping(value = { "/services/rest", "/services/rest/*", "/services/rest/**/*" })
public final void proxyAjaxCall(HttpServletRequest request, HttpServletResponse response) throws IOException {
    log.debug("Prepending service url " + this.servicesUrl + " to " + request.getRequestURI());
    String url = request.getRequestURI().replaceFirst(".*/services/rest/?", this.servicesUrl);
    if (request.getQueryString() != null)
        url = url + "?" + request.getQueryString();

    OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());
    HttpClient client = new HttpClient();
    HttpMethod method = null;/*  w  w  w . ja v a2  s.  c  o m*/
    try {
        log.debug("Proxying ajax request to services REST api via " + request.getMethod());
        // Split this according to the type of request
        if (request.getMethod().equals("GET")) {
            method = new GetMethod(url);
        } else if (request.getMethod().equals("POST")) {
            method = new PostMethod(url);
            // Set any eventual parameters that came with our original
            // request (POST params, for instance)
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                ((PostMethod) method).setParameter(paramName, request.getParameter(paramName));
            }
        } else {
            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

        // Forward the user's groups along with the request
        method.addRequestHeader(HttpClientUtil.SHIBBOLETH_GROUPS_HEADER, GroupsThreadStore.getGroupString());
        method.addRequestHeader("On-Behalf-Of", GroupsThreadStore.getUsername());

        // Execute the method
        client.executeMethod(method);

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {
            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }
        }
        try (InputStream responseStream = method.getResponseBodyAsStream()) {
            int b;
            while ((b = responseStream.read()) != -1) {
                response.getOutputStream().write(b);
            }
        }
        response.getOutputStream().flush();
    } catch (HttpException e) {
        writer.write(e.toString());
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        writer.write(e.toString());
        throw e;
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:net.navasoft.madcoin.backend.services.push.AndroidPushNotificationServiceImpl.java

/**
 * Do send notification./*from  www .j a va2 s .  c  o  m*/
 * 
 * @param notification
 *            the notification
 * @throws PushNotificationException
 *             the push notification exception
 * @since 27/07/2014, 06:48:42 PM
 */
protected void doSendNotification(Notification notification) throws PushNotificationException {
    try {
        PostMethod method = new PostMethod("https://android.apis.google.com/c2dm/send");
        method.addParameter("registration_id", notification.getDeviceToken());
        method.addParameter("collapse_key", "collapse");
        method.addParameter("data.payload", String.valueOf(notification.getBadge()));
        Header header = new Header("Authorization", "GoogleLogin auth=" + notification.getGeneratedToken());
        method.addRequestHeader(header);
        service.executeMethod(method);
        byte[] responseBody = method.getResponseBody();
        String response = new String(responseBody);
        System.out.println(response);
    } catch (HttpException e) {
        e.printStackTrace();
        throw new PushNotificationException("HTTP ", e);
    } catch (IOException e) {
        e.printStackTrace();
        throw new PushNotificationException("IO ", e);
    }

}

From source file:fr.msch.wissl.server.TestPlaylist.java

public void test() throws Exception {
    HttpClient client = new HttpClient();

    RuntimeStats rt = new RuntimeStats();
    rt.songCount.set(15);/*from w w  w . j av a  2  s  . com*/
    rt.albumCount.set(5);
    rt.artistCount.set(2);
    rt.playlistCount.set(0);
    rt.userCount.set(2);
    rt.playtime.set(15);
    rt.downloaded.set(0);
    this.addMusicFolder(new File("src/test/resources/data").getAbsolutePath(), rt);

    rt.songCount.set(24);
    rt.albumCount.set(6);
    rt.artistCount.set(3);
    rt.playtime.set(24);
    this.addMusicFolder(new File("src/test/resources/data2").getAbsolutePath(), rt);

    // create playlist with no name: 400
    PostMethod post = new PostMethod(URL + "playlist/create");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    assertEquals(400, post.getStatusCode());

    // create playlist 'foo'
    post = new PostMethod(URL + "playlist/create");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("name", "foo");
    client.executeMethod(post);
    assertEquals(200, post.getStatusCode());
    JSONObject obj = new JSONObject(post.getResponseBodyAsString());
    Playlist foo = new Playlist(obj.getJSONObject("playlist").toString());
    assertEquals("foo", foo.name);
    assertEquals(0, foo.songs);
    assertEquals(0, foo.playtime);

    // create playlist 'foo' again: returns the same playlist
    post = new PostMethod(URL + "playlist/create");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("name", "foo");
    client.executeMethod(post);
    assertEquals(200, post.getStatusCode());
    obj = new JSONObject(post.getResponseBodyAsString());
    assertEquals(foo, new Playlist(obj.getJSONObject("playlist").toString()));

    // create playlist 'foo' as admin: creates another playlist
    post = new PostMethod(URL + "playlist/create");
    post.addRequestHeader("sessionId", admin_sessionId);
    post.addParameter("name", "foo");
    client.executeMethod(post);
    assertEquals(200, post.getStatusCode());
    obj = new JSONObject(post.getResponseBodyAsString());
    Playlist pl = new Playlist(obj.getJSONObject("playlist").toString());
    assertNotSame(foo, pl);

    // playlists for user: 'foo'
    GetMethod get = new GetMethod(URL + "playlists");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(1, obj.getJSONArray("playlists").length());
    assertEquals(foo, new Playlist(obj.getJSONArray("playlists").get(0).toString()));

    // playlists/id for user: 'foo'
    get = new GetMethod(URL + "playlists/" + user_userId);
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(1, obj.getJSONArray("playlists").length());
    assertEquals(foo, new Playlist(obj.getJSONArray("playlists").get(0).toString()));

    // remove playlist without argument: 400
    post = new PostMethod(URL + "playlists/remove");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    assertEquals(400, post.getStatusCode());

    // remove admin 'foo' playlist as user: 403
    post = new PostMethod(URL + "playlists/remove");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("playlist_ids[]", "" + pl.id);
    client.executeMethod(post);
    assertEquals(403, post.getStatusCode());

    // remove admin 'foo'
    post = new PostMethod(URL + "playlists/remove");
    post.addRequestHeader("sessionId", admin_sessionId);
    post.addParameter("playlist_ids[]", "" + pl.id);
    client.executeMethod(post);
    assertEquals(204, post.getStatusCode());

    // playlists for admin: 'none'
    get = new GetMethod(URL + "playlists");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("playlists").length());

    // playlists/id for admin: 'none'
    get = new GetMethod(URL + "playlists/" + admin_userId);
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("playlists").length());

    // playlist/create-add with no name : 400
    post = new PostMethod(URL + "playlist/create-add");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    assertEquals(400, post.getStatusCode());

    // playlist/create-add 'bar' with no songs
    post = new PostMethod(URL + "playlist/create-add");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("name", "bar");
    client.executeMethod(post);
    assertEquals(200, post.getStatusCode());
    obj = new JSONObject(post.getResponseBodyAsString());
    assertEquals(0, obj.getInt("added"));
    Playlist bar = new Playlist(obj.getJSONObject("playlist").toString());
    assertEquals("bar", bar.name);
    assertEquals(0, bar.playtime);
    assertEquals(0, bar.songs);

    int[] song_ids = new int[4];
    int album_id;

    // search for 'o': 4 songs, 1 album with 1 song
    get = new GetMethod(URL + "search/o");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    JSONArray songs = obj.getJSONArray("songs");
    for (int i = 0; i < 4; i++) {
        song_ids[i] = songs.getJSONObject(i).getInt("id");
    }
    JSONObject ok = obj.getJSONArray("albums").getJSONObject(0);
    album_id = ok.getInt("id");

    // playlist/create-add 'bar' with songs
    post = new PostMethod(URL + "playlist/create-add");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("name", "bar");
    post.addParameter("song_ids[]", "" + song_ids[0]);
    post.addParameter("song_ids[]", "" + song_ids[1]);
    post.addParameter("song_ids[]", "" + song_ids[2]);
    post.addParameter("song_ids[]", "" + song_ids[3]);
    post.addParameter("album_ids[]", "" + album_id);
    client.executeMethod(post);
    assertEquals(200, post.getStatusCode());
    obj = new JSONObject(post.getResponseBodyAsString());
    assertEquals(5, obj.getInt("added"));
    bar = new Playlist(obj.getJSONObject("playlist").toString());
    assertEquals("bar", bar.name);
    assertEquals(5, bar.playtime);
    assertEquals(5, bar.songs);

    // check song list in 'bar'
    get = new GetMethod(URL + "playlist/" + bar.id + "/songs");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals("bar", obj.getString("name"));
    JSONArray arr = obj.getJSONArray("playlist");
    assertEquals(5, arr.length());
    for (int i = 0; i < 4; i++) {
        assertEquals(new Song(songs.getJSONObject(i).toString()), new Song(arr.getJSONObject(i).toString()));
    }
    Song s5 = new Song(arr.getJSONObject(4).toString());
    assertEquals("Ok", s5.album_name);

    // playlist/remove song as wrong user
    post = new PostMethod(URL + "playlist/" + bar.id + "/remove");
    post.addRequestHeader("sessionId", admin_sessionId);
    post.addParameter("song_ids[]", "" + song_ids[0]);
    client.executeMethod(post);
    assertEquals(403, post.getStatusCode());

    // playlist/remove 2 songs
    post = new PostMethod(URL + "playlist/" + bar.id + "/remove");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("song_ids[]", "" + song_ids[1]);
    post.addParameter("song_ids[]", "" + song_ids[2]);
    client.executeMethod(post);
    assertEquals(204, post.getStatusCode());

    // check song list
    get = new GetMethod(URL + "playlist/" + bar.id + "/songs");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals("bar", obj.getString("name"));
    arr = obj.getJSONArray("playlist");
    assertEquals(3, arr.length());
    assertEquals(new Song(songs.getJSONObject(0).toString()), new Song(arr.getJSONObject(0).toString()));
    assertEquals(new Song(songs.getJSONObject(3).toString()), new Song(arr.getJSONObject(1).toString()));
    assertEquals(s5, new Song(arr.getJSONObject(2).toString()));

    // re-check with song/id/pos
    get = new GetMethod(URL + "playlist/" + bar.id + "/song/0");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song");
    assertEquals(new Song(songs.getJSONObject(0).toString()), new Song(obj.toString()));

    // 2nd song
    get = new GetMethod(URL + "playlist/" + bar.id + "/song/1");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song");
    assertEquals(new Song(songs.getJSONObject(3).toString()), new Song(obj.toString()));

    // 3rd song
    get = new GetMethod(URL + "playlist/" + bar.id + "/song/2");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song");
    assertEquals(s5, new Song(obj.toString()));

    // no more song in playlist
    get = new GetMethod(URL + "playlist/" + bar.id + "/song/3");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(404, get.getStatusCode());

    // playlist/create-add 'bar' with other songs and clear
    post = new PostMethod(URL + "playlist/create-add");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("name", "bar");
    post.addParameter("clear", "true");
    post.addParameter("album_ids[]", "" + album_id);
    client.executeMethod(post);
    assertEquals(200, post.getStatusCode());
    obj = new JSONObject(post.getResponseBodyAsString());
    assertEquals(1, obj.getInt("added"));
    bar = new Playlist(obj.getJSONObject("playlist").toString());
    assertEquals("bar", bar.name);
    assertEquals(1, bar.playtime);
    assertEquals(1, bar.songs);

    // playlist/add as admin: 403
    post = new PostMethod(URL + "playlist/" + bar.id + "/add");
    post.addRequestHeader("sessionId", admin_sessionId);
    post.addParameter("clear", "true");
    post.addParameter("song_ids", "" + s5.id);
    client.executeMethod(post);
    assertEquals(403, post.getStatusCode());

    // playlist/add with duplicate songs: 400
    post = new PostMethod(URL + "playlist/" + bar.id + "/add");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("clear", "true");
    post.addParameter("song_ids[]", "" + song_ids[0]);
    post.addParameter("song_ids[]", "" + song_ids[0]);
    post.addParameter("album_ids[]", "" + album_id);
    client.executeMethod(post);
    assertEquals(500, post.getStatusCode());

    // playlist/add a couple songs w/ clear
    post = new PostMethod(URL + "playlist/" + bar.id + "/add");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("clear", "true");
    post.addParameter("song_ids[]", "" + song_ids[0]);
    post.addParameter("song_ids[]", "" + song_ids[2]);
    client.executeMethod(post);
    assertEquals(200, post.getStatusCode());
    obj = new JSONObject(post.getResponseBodyAsString());
    assertEquals(2, obj.getInt("added"));
    pl = new Playlist(obj.getJSONObject("playlist").toString());
    assertEquals(2, pl.playtime);
    assertEquals(2, pl.songs);
    assertEquals("bar", pl.name);

    // check song list
    get = new GetMethod(URL + "playlist/" + pl.id + "/songs");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals("bar", obj.getString("name"));
    arr = obj.getJSONArray("playlist");
    assertEquals(2, arr.length());
    assertEquals(new Song(songs.getJSONObject(0).toString()), new Song(arr.getJSONObject(0).toString()));
    assertEquals(new Song(songs.getJSONObject(2).toString()), new Song(arr.getJSONObject(1).toString()));

    // re-check with song/id/pos
    get = new GetMethod(URL + "playlist/" + pl.id + "/song/0");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song");
    assertEquals(new Song(songs.getJSONObject(0).toString()), new Song(obj.toString()));

    // 2nd song
    get = new GetMethod(URL + "playlist/" + pl.id + "/song/1");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song");
    assertEquals(new Song(songs.getJSONObject(2).toString()), new Song(obj.toString()));

    // no more song in playlist
    get = new GetMethod(URL + "playlist/" + pl.id + "/song/2");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(404, get.getStatusCode());

    // random playlist with no name : 400
    post = new PostMethod(URL + "playlist/random");
    post.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(post);
    assertEquals(400, post.getStatusCode());

    // random playlist with no song number : 400
    post = new PostMethod(URL + "playlist/random");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("name", "toto");
    client.executeMethod(post);
    assertEquals(400, post.getStatusCode());

    // random playlist with too many songs: 400
    post = new PostMethod(URL + "playlist/random");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("number", "60");
    post.addParameter("name", "toto");
    client.executeMethod(post);
    assertEquals(400, post.getStatusCode());

    // random playlist 'toto'
    post = new PostMethod(URL + "playlist/random");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("number", "15");
    post.addParameter("name", "toto");
    client.executeMethod(post);
    assertEquals(200, post.getStatusCode());
    obj = new JSONObject(post.getResponseBodyAsString());
    assertEquals(15, obj.getInt("added"));
    Playlist rand = new Playlist(obj.getJSONObject("playlist").toString());
    assertEquals(15, rand.playtime);
    assertEquals(15, rand.songs);
    assertEquals("toto", rand.name);

    // get first song
    get = new GetMethod(URL + "playlist/" + rand.id + "/song/0");
    get.addRequestHeader("sessionId", admin_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    Song s = new Song(new JSONObject(get.getResponseBodyAsString()).getJSONObject("song").toString());
    assertEquals(s.id, obj.getInt("first_song"));

    // all random songs should fit in this hashset
    HashSet<Song> randSet = new HashSet<Song>(15);
    get = new GetMethod(URL + "playlist/" + rand.id + "/songs");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals("toto", obj.get("name"));
    arr = obj.getJSONArray("playlist");
    assertEquals(15, arr.length());
    for (int i = 0; i < arr.length(); i++) {
        Song ss = new Song(arr.getJSONObject(i).toString());
        assertFalse(randSet.contains(ss));
        randSet.add(ss);
    }

    // there are 24 songs total in library, try to create a 30 songs playlist
    post = new PostMethod(URL + "playlist/random");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("number", "30");
    post.addParameter("name", "titi");
    client.executeMethod(post);
    assertEquals(200, post.getStatusCode());
    obj = new JSONObject(post.getResponseBodyAsString());
    assertEquals(24, obj.getInt("added"));
    rand = new Playlist(obj.getJSONObject("playlist").toString());
    assertEquals(24, rand.playtime);
    assertEquals(24, rand.songs);
    assertEquals("titi", rand.name);

    // all 24 random songs should fit in this hashset
    randSet = new HashSet<Song>(24);
    get = new GetMethod(URL + "playlist/" + rand.id + "/songs");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals("titi", obj.get("name"));
    arr = obj.getJSONArray("playlist");
    assertEquals(24, arr.length());
    for (int i = 0; i < arr.length(); i++) {
        Song ss = new Song(arr.getJSONObject(i).toString());
        assertFalse(randSet.contains(ss));
        randSet.add(ss);
    }

    // re-create 'titi' with 10 songs
    post = new PostMethod(URL + "playlist/random");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("number", "10");
    post.addParameter("name", "titi");
    client.executeMethod(post);
    assertEquals(200, post.getStatusCode());
    obj = new JSONObject(post.getResponseBodyAsString());
    assertEquals(10, obj.getInt("added"));
    rand = new Playlist(obj.getJSONObject("playlist").toString());
    assertEquals(10, rand.playtime);
    assertEquals(10, rand.songs);
    assertEquals("titi", rand.name);

    // playlists for user: 'foo', 'bar', 'toto', 'titi'
    get = new GetMethod(URL + "playlists");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(4, obj.getJSONArray("playlists").length());
    foo = new Playlist(obj.getJSONArray("playlists").get(0).toString());
    bar = new Playlist(obj.getJSONArray("playlists").get(1).toString());
    Playlist toto = new Playlist(obj.getJSONArray("playlists").get(2).toString());
    Playlist titi = new Playlist(obj.getJSONArray("playlists").get(3).toString());
    assertEquals("foo", foo.name);
    assertEquals(0, foo.songs);
    assertEquals("bar", bar.name);
    assertEquals(2, bar.songs);
    assertEquals("toto", toto.name);
    assertEquals(15, toto.songs);
    assertEquals("titi", titi.name);
    assertEquals(10, titi.songs);

    // remove all 4 user playlists
    post = new PostMethod(URL + "playlists/remove");
    post.addRequestHeader("sessionId", user_sessionId);
    post.addParameter("playlist_ids[]", "" + foo.id);
    post.addParameter("playlist_ids[]", "" + bar.id);
    post.addParameter("playlist_ids[]", "" + toto.id);
    post.addParameter("playlist_ids[]", "" + titi.id);
    client.executeMethod(post);
    assertEquals(204, post.getStatusCode());

    // check there are no more user playlists
    get = new GetMethod(URL + "playlists");
    get.addRequestHeader("sessionId", user_sessionId);
    client.executeMethod(get);
    assertEquals(200, get.getStatusCode());
    obj = new JSONObject(get.getResponseBodyAsString());
    assertEquals(0, obj.getJSONArray("playlists").length());

}