private HttpClient login(PostMethod method) throws Exception {
   if (method.getHostConfiguration().getProtocol() == null) {
     throw new Exception("Protocol not specified");
   }
   HttpClient client = getHttpClient();
   client
       .getState()
       .setCredentials(
           AuthScope.ANY, new UsernamePasswordCredentials(getUsername(), getPassword()));
   configureHttpMethod(method);
   method.addParameter("login", getUsername());
   method.addParameter("password", getPassword());
   client.getParams().setContentCharset("UTF-8");
   client.executeMethod(method);
   if (method.getStatusCode() != 200) {
     throw new Exception("Cannot login: HTTP status code " + method.getStatusCode());
   }
   String response = method.getResponseBodyAsString(1000);
   if (response == null) {
     throw new NullPointerException();
   }
   if (!response.contains("<login>ok</login>")) {
     int pos = response.indexOf("</error>");
     int length = "<error>".length();
     if (pos > length) {
       response = response.substring(length, pos);
     }
     throw new Exception("Cannot login: " + response);
   }
   return client;
 }
Пример #2
0
  public synchronized void updateHtmlEntry(String key, String html) throws HttpException {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(catalogDbURL + "update");
    System.err.println(key);
    postMethod.addParameter("key", key);
    postMethod.addParameter("columns", html);
    try {
      httpClient.executeMethod(postMethod);
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
      try {
        String resp = postMethod.getResponseBodyAsString();
        System.err.println(resp);
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      throw new HttpException("failed to post form.");
    }
  }
Пример #3
0
  public FormValidation validate() throws IOException {

    HttpClient hc = createClient();

    PostMethod post = new PostMethod(url + "Login");
    post.addParameter("userName", getUsername());

    if (getPassword() != null) {
      //          post.addParameter("password",getPassword());
      post.addParameter("password", getPassword().getPlainText());
    } else {
      post.addParameter("password", "");
    }

    hc.executeMethod(post);

    // if the login succeeds, we'll see a redirect
    Header loc = post.getResponseHeader("Location");
    if (loc != null && loc.getValue().endsWith("/Central")) return FormValidation.ok("Success!");

    if (!post.getResponseBodyAsString().contains("SOASTA"))
      return FormValidation.error(getUrl() + " doesn't look like a CloudTest server");

    // if it fails, the server responds with 200!
    return FormValidation.error("Invalid credentials.");
  }
 private PostMethod getLoginMethodFor4x() {
   String url = getUrl() + "/rest/gadget/1.0/login";
   PostMethod postMethod = new PostMethod(url);
   postMethod.addParameter("os_username", getUsername());
   postMethod.addParameter("os_password", getPassword());
   postMethod.addParameter("os_destination", "/success");
   configureHttpMethod(postMethod);
   return postMethod;
 }
  public AccessTokenInfo getAccessToken(String username, String password, String appInstanceId)
      throws AccessTokenException {
    SSLContext ctx;
    String response = "";
    try {
      ctx = SSLContext.getInstance("TLS");

      ctx.init(
          new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
      SSLContext.setDefault(ctx);

      URL url = new URL(tokenURL);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      conn.setHostnameVerifier(
          new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
              return true;
            }
          });
      // System.out.println(conn.getResponseCode());
      conn.disconnect();

      HttpClient httpClient = new HttpClient();

      PostMethod postMethod = new PostMethod(tokenURL);
      postMethod.addParameter(new NameValuePair("grant_type", grantType));
      postMethod.addParameter(new NameValuePair("username", username));
      postMethod.addParameter(new NameValuePair("password", password));
      postMethod.addParameter(new NameValuePair("scope", scope + appInstanceId));

      postMethod.addRequestHeader("Authorization", "Basic " + appToken);
      postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

      httpClient.executeMethod(postMethod);

      response = postMethod.getResponseBodyAsString();
      log.info(response);
      JSONObject jsonObject = new JSONObject(response);

      AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
      accessTokenInfo.setAccess_token(jsonObject.getString("access_token"));
      accessTokenInfo.setRefresh_token(jsonObject.getString("refresh_token"));
      accessTokenInfo.setExpires_in(jsonObject.getInt("expires_in"));
      accessTokenInfo.setToken_type(jsonObject.getString("token_type"));

      return accessTokenInfo;

    } catch (NoSuchAlgorithmException | KeyManagementException | IOException | JSONException e) {

      log.error(e.getMessage());
      throw new AccessTokenException("Configuration Error for Access Token Generation");
    } catch (NullPointerException e) {

      return null;
    }
  }
  /** Test if setParameter overwrites existing parameter values. */
  public void testAddParameterFollowedBySetParameter() throws Exception {
    PostMethod method = new PostMethod("/");

    method.addParameter("param", "a");
    method.addParameter("param", "b");
    method.addParameter("param", "c");
    assertEquals("param=a&param=b&param=c", getRequestAsString(method.getRequestEntity()));
    method.setParameter("param", "a");
    assertEquals("param=a", getRequestAsString(method.getRequestEntity()));
  }
Пример #7
0
  @Override
  public long setTargetVersion(PublishingTargetItem target, long newVersion, String site) {
    long resoponseVersion = -1;
    if (target.getVersionUrl() != null && !target.getVersionUrl().isEmpty()) {
      LOGGER.debug("Set deployment agent version for target {0}", target.getName());
      URL versionUrl = null;
      try {
        versionUrl = new URL(target.getVersionUrl());
      } catch (MalformedURLException e) {
        LOGGER.error("Invalid set version URL for target [%s]", target.getName());
        return resoponseVersion;
      }
      PostMethod postMethod = null;
      HttpClient client = null;
      try {
        postMethod = new PostMethod(target.getVersionUrl());
        postMethod.addParameter(TARGET_REQUEST_PARAMETER, target.getTarget());
        postMethod.addParameter(VERSION_REQUEST_PARAMETER, String.valueOf(newVersion));
        String siteId = target.getSiteId();
        if (StringUtils.isEmpty(siteId)) {
          siteId = site;
        }
        postMethod.addParameter(SITE_REQUEST_PARAMETER, site);
        client = new HttpClient();
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
          String responseText = postMethod.getResponseBodyAsString();
          if (responseText != null && !responseText.isEmpty()) {
            resoponseVersion = Long.parseLong(responseText);
          } else {
            resoponseVersion = 0;
          }
        }

      } catch (Exception e) {
        LOGGER.error(
            "Target {0} responded with error while setting target version. Set version failed for url {1}",
            target.getName(), target.getVersionUrl());

      } finally {
        if (client != null) {
          HttpConnectionManager mgr = client.getHttpConnectionManager();
          if (mgr instanceof SimpleHttpConnectionManager) {
            ((SimpleHttpConnectionManager) mgr).shutdown();
          }
        }
        if (postMethod != null) {
          postMethod.releaseConnection();
        }
        postMethod = null;
        client = null;
      }
    }
    return resoponseVersion;
  }
Пример #8
0
 public void registerMessagingServiceScopes(String consumerKey, String scope) throws Exception {
   HttpClient client = new HttpClient();
   PostMethod method = new PostMethod(ConsumerScopesRegistrationURL);
   Base64 base64 = new Base64();
   String base64Credentials = new String(base64.encode("admin:admin".getBytes()));
   method.addRequestHeader(new Header("Authorization", "Basic " + base64Credentials));
   method.addParameter(OAuth.OAUTH_CONSUMER_KEY, consumerKey);
   method.addParameter("xoauth_scope", scope);
   method.addParameter("xoauth_permission", "sendMessages");
   int status = client.executeMethod(method);
   if (HttpResponseCodes.SC_OK != status) {
     throw new RuntimeException("Scopes can not be registered");
   }
 }
Пример #9
0
 // TODO : the subscriber may need to provide some form of id known
 // to the message receiver so that the receiver can validate that it was indeed
 // the subscriber who asked the service to push the messages;
 // however, the consumerId creates by the subscriber can be enough;
 // Question : what about refresh tokens ?
 public void registerMessagingServiceCallback(
     String consumerKey, String consumerSecret, String callback) throws Exception {
   HttpClient client = new HttpClient();
   PostMethod method = new PostMethod(MessagingServiceCallbackRegistrationURL);
   Base64 base64 = new Base64();
   String base64Credentials = new String(base64.encode("admin:admin".getBytes()));
   method.addRequestHeader(new Header("Authorization", "Basic " + base64Credentials));
   method.addParameter("consumer_id", consumerKey);
   method.addParameter("consumer_secret", consumerSecret);
   method.addParameter("callback_uri", callback);
   int status = client.executeMethod(method);
   if (HttpResponseCodes.SC_OK != status) {
     throw new RuntimeException("Callback Registration failed");
   }
 }
Пример #10
0
  private PostMethod convertHttpServletRequestToPostMethod(String url, HttpServletRequest request) {
    PostMethod postMethod = new PostMethod(url);

    for (Enumeration headers = request.getHeaderNames(); headers.hasMoreElements(); ) {
      String headerName = (String) headers.nextElement();
      String headerValue = (String) request.getHeader(headerName);
      postMethod.addRequestHeader(headerName, headerValue);
    }

    postMethod.removeRequestHeader("Host");
    postMethod.addRequestHeader("Host", request.getRequestURL().toString());

    for (Enumeration names = request.getParameterNames(); names.hasMoreElements(); ) {
      String paramName = (String) names.nextElement();
      String paramValue = (String) request.getParameter(paramName);
      postMethod.addParameter(paramName, paramValue);
    }

    StringBuilder requestBody = new StringBuilder();
    try {
      BufferedReader reader = request.getReader();
      String line;
      while (null != (line = reader.readLine())) {
        requestBody.append(line);
      }
      reader.close();
    } catch (IOException e) {
      requestBody.append("");
    }

    postMethod.setRequestEntity(new StringRequestEntity(requestBody.toString()));

    return postMethod;
  }
Пример #11
0
  @Action("SignModeCheck")
  public String signModeCheck() throws Exception {
    try {
      HttpClient client = new HttpClient();
      String url = "http://127.0.0.1:" + getServerPort() + "/service/";
      logger.debug("url: " + url);

      CommunicationVo requestVo = new CommunicationVo();
      requestVo.setTradeCode("000001");
      requestVo.putParam("signMode", this.signVo.getSignMode());
      requestVo.putParam("certDn", this.signVo.getCertDn());
      PostMethod postMethod = new PostMethod(url);
      postMethod.addParameter("json", requestVo.toJson());

      client.executeMethod(postMethod);

      String resp = postMethod.getResponseBodyAsString().trim();

      postMethod.releaseConnection();
      logger.info("resp: " + resp);

      CommunicationVo respVo = CommunicationVo.getInstancefromJson(resp);
      if (!"0000".equals(respVo.getStatus())) {
        throw new ServiceException(respVo.getMessage());
      }
      this.dwzResp.ajaxSuccessForward(respVo.getMessage());
      this.dwzResp.setAlertClose(Boolean.valueOf(false));
    } catch (Exception e) {
      logger.error(ExceptionUtils.getStackTrace(e));
      this.dwzResp.errorForward(e.getMessage());
      return "dwz";
    }
    return "dwz";
  }
  public String jasperAuthen(String username, String password) throws HttpException, IOException {
    logger.info("Authenticate : Jasper Report Server");

    Header[] headers = null;
    String sessionCookie = "";

    this.httpClient = new HttpClient();
    PostMethod mPost = new PostMethod(restLoginUrl);

    Header mtHeader = new Header();
    mtHeader.setName("content-type");
    mtHeader.setValue("application/x-www-form-urlencoded");
    mtHeader.setName("accept");

    mPost.addParameter("j_username", username);
    mPost.addParameter("j_password", password);
    mPost.addRequestHeader(mtHeader);

    httpClient.executeMethod(mPost);

    headers = mPost.getResponseHeaders();
    mPost.releaseConnection();

    sessionCookie = headers[2].getValue();
    logger.debug("SessionCookie is {}", sessionCookie);

    return sessionCookie;
  }
Пример #13
0
 /**
  * post
  *
  * @param url
  * @param params
  * @param token
  * @return
  * @throws ApiException
  */
 public static String post(String url, PostParameter[] params, String token) throws IOException {
   PostMethod postMethod = new PostMethod(url);
   for (int i = 0; i < params.length; i++) {
     postMethod.addParameter(params[i].getName(), params[i].getValue());
   }
   HttpMethodParams param = postMethod.getParams();
   param.setContentCharset(DEFAULTCHAESET);
   return httpRequest(postMethod, token);
 }
  /** Test the return value of the PostMethod#removeParameter. */
  public void testRemoveParameterReturnValue() throws Exception {
    PostMethod method = new PostMethod("/");

    method.addParameter("param", "whatever");
    assertTrue(
        "Return value of the method is expected to be true", method.removeParameter("param"));
    assertFalse(
        "Return value of the method is expected to be false", method.removeParameter("param"));
  }
Пример #15
0
  private void httpDeleteProject(String url, ExtractionProject eProject) throws Exception {
    PostMethod method = null;
    try {
      HttpClient client = new HttpClient();
      client.getParams().setParameter("http.connection.timeout", new Integer(8000));
      method = new PostMethod(url);
      method.addParameter("PROJECT_ID", eProject.getIdProyecto());
      method.addParameter("PROJECT_NAME", eProject.getNombreProyecto());

      int statusCode1 = client.executeMethod(method);
      logger.info("statusLine>>> " + method.getStatusLine() + " || statusCode>>> " + statusCode1);

    } catch (Exception e) {
      logger.error("No se ha podido eliminar el proyecto. " + e, e);
      throw e;
    } finally {
      if (method != null) method.releaseConnection();
    }
  }
  public static void main(String[] args) {
    Date now;
    now = new Date();

    System.out.println("Time is :" + now);
    // Create Repetitively task for every 1 secs
    HttpClient client = null;
    PostMethod method = null;
    JSONObject joResponse = null;

    try {
      client = new HttpClient();

      // method = new PostMethod("http://23.23.129.228/getLocations.php");
      method = new PostMethod("http://54.235.163.80/getLocations.php");
      method.addParameter("f", "json");
      method.setRequestHeader("Connection", "close");
      int statusCode = client.executeMethod(method);
      System.out.println(statusCode);
      String responseStream = method.getResponseBodyAsString();

      HashSet<String> activeLocations = new HashSet<String>();

      if (statusCode == HttpURLConnection.HTTP_OK
          && responseStream.trim().startsWith("{")
          && responseStream.trim().endsWith("}")) {

        StringBuilder keyStrbuildr = new StringBuilder();

        joResponse = JSONObject.fromObject(responseStream);
        // JSONObject locationresp = (JSONObject) joResponse.get("data");

        System.out.println(joResponse.getString("data"));
        System.out.println(!joResponse.getString("data").equals("[]"));

        /*System.out.println(locationresp);
        for (Object key: locationresp.keySet()) {

        	String keyStr = (String) key;
        	activeLocations.add(keyStr.split(":")[0]);
        	keyStrbuildr.append("'")
        		.append(keyStr.split(":")[0])
        		.append("',");
        }

        	System.out.println(keyStrbuildr);*/

      } else {
        System.out.println("no response from the wpt server");
      }

    } catch (Exception e) {
      System.out.println(e);
    }
  }
  /** Test that parameters can be added and removed. */
  public void testAddRemoveParametersToParamServlet() throws Exception {
    PostMethod method = new PostMethod("/");

    method.addParameter(new NameValuePair("pname0", "pvalue0"));
    method.addParameter(new NameValuePair("pname1", "pvalue1"));
    method.addParameter(new NameValuePair("pname2", "pvalue2"));
    method.addParameter(new NameValuePair("pname3", "pvalue3"));
    method.removeParameter("pname0");
    method.removeParameter("pname3");

    this.server.setHttpService(new EchoService());
    try {
      this.client.executeMethod(method);
      assertEquals(200, method.getStatusCode());
      String body = method.getResponseBodyAsString();
      assertEquals("pname1=pvalue1&pname2=pvalue2", body);
    } finally {
      method.releaseConnection();
    }
  }
 private HttpMethod getPostMethod(BlogQueryParameter param) {
   PostMethod method = new PostMethod(param.getMethodUrl());
   // Set the parameters
   Collection<QueryParameter> paramColl = param.getAllParameters();
   for (QueryParameter qp : paramColl) {
     String key = getParamStringMap().get(qp);
     if (key != null) {
       method.addParameter(key, param.getParameter(qp));
     }
   }
   return method;
 }
Пример #19
0
 public Response post(String url, PostParameter[] params, Boolean WithTokenHeader, String token)
     throws WeiboException {
   log("Request:");
   log("POST" + url);
   PostMethod postMethod = new PostMethod(url);
   for (int i = 0; i < params.length; i++) {
     postMethod.addParameter(params[i].getName(), params[i].getValue());
   }
   HttpMethodParams param = postMethod.getParams();
   param.setContentCharset("UTF-8");
   return httpRequest(postMethod, WithTokenHeader, token);
 }
  private String sendRequest(TicketsRequest request) throws HttpException, IOException {

    String html = "";
    GetMethod get = new GetMethod(url2);
    client.executeMethod(get);

    int statusCodeInit = client.executeMethod(get);
    if (statusCodeInit != HttpStatus.SC_OK) {
      logger.error("sendRequest method failed. Get method failed: " + get.getStatusLine());
      return null;
    } else {
      html = IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8");
    }
    parseToken(html);

    client.getHttpConnectionManager().getParams().setSoTimeout(10000);
    PostMethod post = new PostMethod(URL);

    post.addRequestHeader("Accept", "*/*");
    post.addRequestHeader("Accept-Encoding", "gzip, deflate");
    post.addRequestHeader("Accept-Language", "uk,ru;q=0.8,en-US;q=0.5,en;q=0.3");
    //		post.addRequestHeader("Cache-Control", "no-cache");
    post.addRequestHeader("Connection", "keep-alive");
    //		post.addRequestHeader("Content-Length", "288"); //202. 196
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    post.addRequestHeader("GV-Ajax", "1");
    post.addRequestHeader("GV-Referer", "http://booking.uz.gov.ua/");
    post.addRequestHeader("GV-Screen", "1920x1080");
    post.addRequestHeader("GV-Token", token);
    post.addRequestHeader("GV-Unique-Host", "1");
    post.addRequestHeader("Host", "booking.uz.gov.ua");
    //		post.addRequestHeader("Pragma", "no-cache");
    post.addRequestHeader("Origin", "http://booking.uz.gov.ua");
    post.addRequestHeader("Referer", "http://booking.uz.gov.ua/");
    post.addRequestHeader(
        "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/39.0");

    post.addParameter("another_ec", "0");
    post.addParameter("date_dep", new SimpleDateFormat("dd.MM.yyyy").format(request.date));
    post.addParameter("search", "");
    post.addParameter("station_from", request.from.getName());
    post.addParameter("station_id_from", request.from.getStationId());
    post.addParameter("station_id_till", request.till.getStationId());
    post.addParameter("station_till", request.till.getName());
    post.addParameter("time_dep", "00:00");
    post.addParameter("time_dep_till", "");

    int statusCode = client.executeMethod(post);
    if (statusCode != HttpStatus.SC_OK) {
      logger.error("sendRequest method failed. Post method failed: " + post.getStatusLine());
      return null;
    }

    return post.getResponseBodyAsString();
  }
Пример #21
0
 @Override
 public Result post(HttpUrl url, String encoding, String cookie, Map<String, String> headers) {
   String realUrl = url.getRenderedUrl();
   PostMethod method = new PostMethod(realUrl);
   if (url.getQueryParam() != null) {
     for (Entry<String, String> entry : url.getQueryParam().entrySet()) {
       method.addParameter(new NameValuePair(entry.getKey(), entry.getValue()));
     }
   }
   Result result = excuteMethod(method, cookie, headers);
   result.setResultEncoding(encoding);
   return result;
 }
Пример #22
0
 public String registerMessagingService(String consumerKey) throws Exception {
   HttpClient client = new HttpClient();
   PostMethod method = new PostMethod(ConsumerRegistrationURL);
   Base64 base64 = new Base64();
   String base64Credentials = new String(base64.encode("admin:admin".getBytes()));
   method.addRequestHeader(new Header("Authorization", "Basic " + base64Credentials));
   method.addParameter(OAuth.OAUTH_CONSUMER_KEY, consumerKey);
   int status = client.executeMethod(method);
   if (HttpResponseCodes.SC_OK != status) {
     throw new RuntimeException("Registration failed");
   }
   // check that we got all tokens
   Map<String, String> response = OAuth.newMap(OAuth.decodeForm(method.getResponseBodyAsString()));
   String secret = response.get("xoauth_consumer_secret");
   if (secret == null) {
     throw new RuntimeException("No secret available");
   }
   return secret;
 }
Пример #23
0
  /**
   * http 통신을 한다.POST 방식
   *
   * @param url
   * @param params
   * @return 서버에서 받은 body 스트링
   */
  public String execute(String url, String queryString, Map params, boolean sslExceptionIgnore)
      throws HttpNetAgentException {

    PostMethod postMethod = null;
    String responseBody = null;

    postMethod = new PostMethod(url);

    java.util.Iterator ith = params.keySet().iterator();
    while (ith.hasNext()) {
      String paramName = (String) ith.next();
      String paramValue = (String) params.get(paramName);
      postMethod.addParameter(paramName, paramValue);
    }

    postMethod.setQueryString(queryString);
    responseBody = send(postMethod, sslExceptionIgnore);

    return responseBody;
  }
Пример #24
0
  @Action(
      value = "FindDnList",
      results = {
        @org.apache.struts2.convention.annotation.Result(
            location = "/WEB-INF/jsp/pingan/SignDnList.jsp")
      })
  public String findDnList() {
    try {
      HttpClient client = new HttpClient();
      String url = "http://127.0.0.1:" + getServerPort() + "/service/";
      logger.debug("url: " + url);

      CommunicationVo requestVo = new CommunicationVo();
      requestVo.setTradeCode("000002");
      requestVo.putParam("signMode", this.signVo.getSignMode());

      PostMethod postMethod = new PostMethod(url);
      postMethod.addParameter("json", requestVo.toJson());

      client.executeMethod(postMethod);

      String resp = postMethod.getResponseBodyAsString().trim();

      postMethod.releaseConnection();
      logger.info("resp: " + resp);

      CommunicationVo respVo = CommunicationVo.getInstancefromJson(resp);
      if (!"0000".equals(respVo.getStatus())) {
        throw new ServiceException(respVo.getMessage());
      }
      this.req.setAttribute("dnList", respVo.getListParam("dnList"));
    } catch (Exception e) {
      logger.error(ExceptionUtils.getStackTrace(e));
      this.dwzResp.errorForward("获取证书DN列表失败");
      return "dwz";
    }
    return "success";
  }
Пример #25
0
  protected void processPostMethod(
      PostMethod postMethod, List<Http.FilePart> fileParts, Map<String, String> parts) {

    if ((fileParts == null) || fileParts.isEmpty()) {
      if (parts != null) {
        for (Map.Entry<String, String> entry : parts.entrySet()) {
          String value = entry.getValue();

          if (Validator.isNotNull(value)) {
            postMethod.addParameter(entry.getKey(), value);
          }
        }
      }
    } else {
      List<Part> partsList = new ArrayList<Part>();

      if (parts != null) {
        for (Map.Entry<String, String> entry : parts.entrySet()) {
          String value = entry.getValue();

          if (Validator.isNotNull(value)) {
            StringPart stringPart = new StringPart(entry.getKey(), value);

            partsList.add(stringPart);
          }
        }
      }

      for (Http.FilePart filePart : fileParts) {
        partsList.add(toCommonsFilePart(filePart));
      }

      MultipartRequestEntity multipartRequestEntity =
          new MultipartRequestEntity(partsList.toArray(new Part[0]), postMethod.getParams());

      postMethod.setRequestEntity(multipartRequestEntity);
    }
  }
Пример #26
0
  public void testExecuteDeviceUpdate() {
    String json =
        "{\n"
            + "    \"client\": {\n"
            + "        \"username\": \"00:14:49:0D:00:00\",\n"
            + "        \"model\": \"IHO-10004K\",\n"
            + "        \"datatype\": \"1\",\n"
            + "        \"androidsdk\": \"19\",\n"
            + "\t\t\"macadress\":\"101\",\n"
            + "        \"signtype\": \"test\",\n"
            + "        \"testmode\": \"false\",\n"
            + "        \"firmwareversion\": \"2.0\",\n"
            + "        \"hardwareversion\": \"00000030\",\n"
            + "        \"apkversion\": \"2.6\"\n"
            + "\t\t}\n"
            + "}";

    HttpClientRequestImpl client = new HttpClientRequestImpl();
    PostMethod method = new PostMethod(HOST + "main.html");
    method.addParameter("json", json);
    String s = client.httpPostRequest(method);
    System.out.println(s);
  }
Пример #27
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    System.out.println("Begin OAuth");

    String accessToken = (String) request.getSession().getAttribute(ACCESS_TOKEN);

    if (accessToken == null) {

      String instanceUrl = null;

      if (request.getRequestURI().endsWith("oauth")) {
        // we need to send the user to authorize
        response.sendRedirect(authUrl);
        return;
      } else {
        System.out.println("Auth successful - got callback");

        String code = request.getParameter("code");

        HttpClient httpclient = new HttpClient();

        PostMethod post = new PostMethod(tokenUrl);
        post.addParameter("code", code);
        post.addParameter("grant_type", "authorization_code");
        /*
        post.addParameter("client_id", clientId);
        post.addParameter("client_secret", clientSecret);
        post.addParameter("redirect_uri", redirectUri);
        */
        post.addParameter(
            "client_id",
            "3MVG9GiqKapCZBwEQ.zsKlrXNZsLKRIt5N6_xlGkEu..UgAJSnXmX3gVC_pbaPnEjpu.4Q9G8oNqY6xjTdqC1");
        post.addParameter("client_secret", "3751930497380396254");
        post.addParameter("redirect_uri", "https://cs11.salesforce.com/");

        try {
          httpclient.executeMethod(post);

          try {
            JSONObject authResponse =
                new JSONObject(
                    new JSONTokener(new InputStreamReader(post.getResponseBodyAsStream())));
            System.out.println("xAuth response: " + authResponse.toString(2));

            accessToken = authResponse.getString("access_token");

            // Instance URL is Salesforce specific.
            instanceUrl = authResponse.getString("instance_url");

            System.out.println("Got access token: " + accessToken);
          } catch (JSONException e) {
            e.printStackTrace();
            throw new ServletException(e);
          }
        } catch (HttpException e) {
          e.printStackTrace();
          throw new ServletException(e);
        } finally {
          post.releaseConnection();
        }
      }

      // Set a session attribute so that other servlets can get the access
      // token
      request.getSession().setAttribute(ACCESS_TOKEN, accessToken);

      // We also get the instance URL from the OAuth response, so set it
      // in the session too
      request.getSession().setAttribute(INSTANCE_URL, instanceUrl);
    }

    response.sendRedirect(request.getContextPath() + "/index.html");
  }
Пример #28
0
  // 授权,生成access_token
  // 使用情形:①程序初始化;②每隔一天左右重新授权access_token
  public static void generate() {
    initAccountInfo();
    accessToken.clear();

    logger.info("用户授权中...");
    try {
      // https://api.weibo.com/oauth2/authorize?client_id=750123511&redirect_uri=https://api.weibo.com/oauth2/default.html&response_type=code
      String url = "https://api.weibo.com/oauth2/authorize";
      String redirectUri = "https://api.weibo.com/oauth2/default.html";

      for (int i = 0; i < accountInfo.size(); i++) {
        // 获取应用的信息
        clientId = WeiboConfig.getValue("client_ID");
        clientSecret = WeiboConfig.getValue("client_SERCRET");

        // 构造授权的url参数
        PostMethod postMethod = new PostMethod(url);
        postMethod.addParameter("client_id", clientId);
        postMethod.addParameter("redirect_uri", redirectUri);
        postMethod.addParameter("userId", accountInfo.get(i).getUserId());
        postMethod.addParameter("passwd", accountInfo.get(i).getPasswd());
        postMethod.addParameter("isLoginSina", "0");
        postMethod.addParameter("action", "submit");
        postMethod.addParameter("response_type", "code");
        HttpMethodParams param = postMethod.getParams();
        param.setContentCharset("UTF-8");

        // 伪造头部域信息
        List<Header> headers = new ArrayList<Header>();
        headers.add(
            new Header(
                "Referer",
                "https://api.weibo.com/oauth2/authorize?client_id="
                    + clientId
                    + "&redirect_uri="
                    + redirectUri
                    + "&from=sina&response_type=code"));
        headers.add(new Header("Host", "api.weibo.com"));
        headers.add(
            new Header(
                "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"));

        // 发送HTTP请求
        HttpClient client = new HttpClient();
        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        client.executeMethod(postMethod);

        // 获取授权响应
        int status = postMethod.getStatusCode();
        if (status == 302) {
          Header location = postMethod.getResponseHeader("location");
          if (location != null) {
            String retUrl = location.getValue();
            int begin = retUrl.indexOf("code=");
            int end = retUrl.length();
            String code = retUrl.substring(begin + 5, end);
            if (code != null) {
              Oauth oauth = new Oauth();
              String token = oauth.getAccessTokenByCode(code).getAccessToken();
              accessToken.add(token);
              logger.info("第" + (i + 1) + "个access_token:" + token);
            }
          }
        } else {
          logger.error("第" + (i + 1) + "个用户授权失败了!");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("授权发生异常!");
    }
  }
  public static void main(String[] args) throws Exception {
    /**
     * Use the key and secret provided when you registered your application
     * http://www.flickr.com/services/api/keys/apply/
     */
    String key = "";
    String secret = "";

    /**
     * This example assumes that you have uploaded a photo to your Flickr account.
     *
     * <p>The photo id can be found in the URL of the photo
     * http://flickr.com/photos/xxxxxxx@N03/<use_this_photo_id>/
     */
    String photoId = "";

    /**
     * Request a frob to identify the login session. This call requires a signature. The signature
     * starts with your shared secret and is followed by your API key and the method name. The API
     * key and method name are prepended by the words "api_key" and "method" as shown in the
     * following line.
     */
    String methodGetFrob = "flickr.auth.getFrob";
    String sig = secret + "api_key" + key + "method" + methodGetFrob;

    /** The API signature must be MD5 encoded and appended to the request */
    String signature = MD5(sig);

    String request =
        "http://api.flickr.com/services/rest/?method="
            + methodGetFrob
            + "&api_key="
            + key
            + "&api_sig="
            + signature;
    System.out.println("GET frob request: " + request);

    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(request);

    // Send GET request
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
      System.err.println("Method failed: " + method.getStatusLine());
    }

    InputStream rstream = null;

    // Get the response body
    rstream = method.getResponseBodyAsStream();

    // Retrieve the XML response to the frob request and get the frob value.
    Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(rstream);

    String frob = null;

    // Check if frob is in the response
    NodeList frobResponse = response.getElementsByTagName("frob");
    Node frobNode = frobResponse.item(0);
    if (frobNode != null) {
      frob = frobNode.getTextContent();
      System.out.println("Successfully retrieved frob: " + frob);
    } else {
      printFlickrError(response);
      return;
    }
    System.out.println("Get frob XML response:");
    /**
     * Create a Flickr login link
     * http://www.flickr.com/services/auth/?api_key=[api_key]&perms=[perms]&frob=[frob]&api_sig=[api_sig]
     * We are using "write" for the perms value because we will be rotating an image.
     */
    sig = secret + "api_key" + key + "frob" + frob + "permswrite";
    signature = MD5(sig);
    request =
        "http://www.flickr.com/services/auth/?api_key="
            + key
            + "&perms=write&frob="
            + frob
            + "&api_sig="
            + signature;

    /** Copy/paste the generated link into your favorite web browser and follow the instructions */
    System.out.println(
        "Browse to the following flickr url to authenticate yourself and then press enter.");
    System.out.println(request);
    BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
    String line = infile.readLine();

    /**
     * Get auth token using frob. Once again, a signature is required for authenticated calls to the
     * Flickr API.
     */
    String methodGetToken = "flickr.auth.getToken";
    sig = secret + "api_key" + key + "frob" + frob + "method" + methodGetToken;
    signature = MD5(sig);
    request =
        "http://api.flickr.com/services/rest/?method="
            + methodGetToken
            + "&api_key="
            + key
            + "&frob="
            + frob
            + "&api_sig="
            + signature;
    System.out.println("Token request: " + request);

    method = new GetMethod(request);

    // Send GET request
    statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
      System.err.println("Method failed: " + method.getStatusLine());
    }

    rstream = null;

    // Get the response body
    rstream = method.getResponseBodyAsStream();
    /** Retrieve the XML response to the token request and get the token value */
    response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(rstream);

    String token = null;

    // Check if token is in the response
    NodeList tokenResponse = response.getElementsByTagName("token");
    Node tokenNode = tokenResponse.item(0);
    if (tokenNode != null) {
      token = tokenNode.getTextContent();
      System.out.println("Successfully retrieved token: " + token);
    } else {
      printFlickrError(response);
      return;
    }

    /**
     * Now that we have authenticated with Flickr and obtained an auth token with write privileges,
     * it's time to rotate the image.
     *
     * <p>http://api.flickr.com/services/rest/?method=flickr.photos.transform.rotate&
     * api_key=[api_key]&photo_id=[photo_id]&degrees=180&auth_token=[auth_token]&api_sig=[api_sig]
     */
    String methodRotate = "flickr.photos.transform.rotate";
    sig =
        secret
            + "api_key"
            + key
            + "auth_token"
            + token
            + "degrees180"
            + "method"
            + methodRotate
            + "photo_id"
            + photoId;
    signature = MD5(sig);

    /**
     * Create POST data for rotate request. The Flickr API documentation specifies that calls to
     * flickr.photos.transform.rotate be made via HTTP POST.
     */
    request = "http://api.flickr.com/services/rest/";

    PostMethod pmethod = new PostMethod(request);

    pmethod.addParameter("method", methodRotate);
    pmethod.addParameter("photo_id", photoId);
    pmethod.addParameter("degrees", "180");
    pmethod.addParameter("api_key", key);
    pmethod.addParameter("auth_token", token);
    pmethod.addParameter("api_sig", signature);

    // Send POST request
    statusCode = client.executeMethod(pmethod);

    if (statusCode != HttpStatus.SC_OK) {
      System.err.println("Method failed: " + pmethod.getStatusLine());
    }

    rstream = null;

    // Get the response body
    rstream = pmethod.getResponseBodyAsStream();

    /** Retrieve the XML response to the rotate request and get the XML response */
    response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(rstream);

    String photoid = null;

    // Check if photoid is in the response
    NodeList rotateResponse = response.getElementsByTagName("photoid");
    Node rotateNode = rotateResponse.item(0);
    if (rotateNode != null) {
      photoid = rotateNode.getTextContent();
      System.out.println("Successfully flipped photo " + photoid);
      System.out.println(
          "Refresh the photo in your web browser and you will see it has been flipped.");
    } else {
      printFlickrError(response);
      return;
    }
  }
Пример #30
0
  public void test() throws Exception {
    HttpClient client = new HttpClient();

    RuntimeStats rt = new RuntimeStats();
    rt.songCount.set(15);
    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: '******'
    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: '******'
    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: '******', '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());
  }