Exemplo n.º 1
0
  @Path("/read")
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response readResponse(String input) throws Exception {
    JSONObject test = new JSONObject(input);
    Datastore ds = MongoConnection.getServer();
    List<ClientObject> clientObjects =
        ds.createQuery(ClientObject.class)
            .filter("client_bs_obj.device_id =", test.getString("client_bs_obj.device_id"))
            .asList();
    Resource resourceO =
        clientObjects
            .get(0)
            .getObjectMap()
            .get(test.getInt("ObjectId"))
            .getObjInstanceMap()
            .get(test.getInt("ObjectInsId"))
            .getResourceMap()
            .get(test.getInt("resourceId"));
    ObjectMapper mapper = new ObjectMapper();
    Resource resourceN = mapper.readValue(test.getString("value"), Resource.class);

    resourceO.getValue().putAll(resourceN.getValue());

    ds.save(clientObjects.get(0));

    CountDownLatch signalRead = Info.getCountDownMessage(test.getString("client_bs_obj.device_id"));
    signalRead.countDown();

    return Response.status(200).entity("success").build();
  }
Exemplo n.º 2
0
  @Test
  public void testUpdatePreference() throws JSONException {

    JSONObject createPreferenceResult =
        mp.createPreference(
            "{'items':[{'title':'Prueba','quantity':1,'currency_id':'ARS','unit_price':10.5}]}");

    String createdPreferenceId = createPreferenceResult.getJSONObject("response").getString("id");

    JSONObject updatePreferenceResult =
        mp.updatePreference(
            createdPreferenceId, "{'items':[{'title':'Modified','quantity':2,'unit_price':2.2}]}");

    assertEquals(updatePreferenceResult.getInt("status"), 200);

    JSONObject getPreferenceResult = mp.getPreference(createdPreferenceId);

    assertEquals(getPreferenceResult.getInt("status"), 200);

    JSONObject obtainedPreference =
        (JSONObject) getPreferenceResult.getJSONObject("response").getJSONArray("items").get(0);

    assertEquals(obtainedPreference.getString("title"), "Modified");
    assertEquals(obtainedPreference.getInt("quantity"), 2);
    assertEquals(obtainedPreference.getDouble("unit_price"), 2, 2d);
  }
Exemplo n.º 3
0
  @Path("/write")
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response writeResponse(String input) throws Exception {

    JSONObject inputObj = new JSONObject(input);
    Datastore ds = MongoConnection.getServer();
    List<ClientObject> clientObjects =
        ds.createQuery(ClientObject.class)
            .filter("client_bs_obj.device_id =", inputObj.getString("client_bs_obj.device_id"))
            .asList();

    ClientObject clientObject = clientObjects.get(0);
    Resource resource1 =
        clientObject
            .getObjectMap()
            .get(inputObj.getInt("ObjectId"))
            .getObjInstanceMap()
            .get(inputObj.getInt("ObjectInsId"))
            .getResourceMap()
            .get(inputObj.getInt("resourceId"));
    resource1.setS_value(inputObj.getString("s_value"));
    ds.save(clientObject);

    CountDownLatch signalRead =
        Info.getCountDownMessage(inputObj.getString("client_bs_obj.device_id"));
    signalRead.countDown();

    return Response.status(200).entity(inputObj.getString("message")).build();
  }
Exemplo n.º 4
0
  @POST
  @Path("/addPcuLabTestRequest")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public String addPcuLabTestRequest(JSONObject pJson) {

    try {

      PcuLabTestRequest request = new PcuLabTestRequest();

      int testID = pJson.getInt("ftest_ID");

      int labID = pJson.getInt("flab_ID");
      int admissionID = pJson.getInt("admintionID");
      int userid = pJson.getInt("ftest_RequestPerson");

      request.setComment(pJson.getString("comment").toString());
      request.setPriority(pJson.getString("priority").toString());
      request.setStatus(pJson.getString("status").toString());
      request.setTest_RequestDate(new Date());
      request.setTest_DueDate(new Date());

      requestDBDriver.addNewLabTestRequest(request, testID, admissionID, labID, userid);

      JSONSerializer jsonSerializer = new JSONSerializer();
      return jsonSerializer.include("pcu_lab_test_request_id").serialize(request);
    } catch (Exception e) {
      System.out.println(e.getMessage());

      return null;
    }
  }
Exemplo n.º 5
0
  @Override
  public Contact checkIFPhoneNumberIsAContactOfUser(JSONObject data) {
    em = PersistenceManager.getEntityManagerFactory().createEntityManager();

    String phone = "";
    int userId = 0;
    try {
      phone = data.getString("phone");
      userId = data.getInt("userId");
    } catch (JSONException e) {
      e.printStackTrace();
    }

    try {
      return (Contact)
          em.createQuery(
                  "SELECT c FROM Contact c WHERE c.phone = '"
                      + phone
                      + "' AND c.user_owner.id = "
                      + userId)
              .getSingleResult();
    } catch (NoResultException e) {
      return null;
    }
  }
  @Override
  protected int checkResponse(URI uri, ClientResponse response) {
    ClientResponse.Status status = response.getClientResponseStatus();
    int errorCode = status.getStatusCode();
    if (errorCode >= 300) {
      JSONObject obj = null;
      int code = 0;
      try {
        obj = response.getEntity(JSONObject.class);
        code = obj.getInt(ScaleIOConstants.ERROR_CODE);
      } catch (Exception e) {
        log.error("Parsing the failure response object failed", e);
      }

      if (code == 404 || code == 410) {
        throw ScaleIOException.exceptions.resourceNotFound(uri.toString());
      } else if (code == 401) {
        throw ScaleIOException.exceptions.authenticationFailure(uri.toString());
      } else {
        throw ScaleIOException.exceptions.internalError(uri.toString(), obj.toString());
      }
    } else {
      return errorCode;
    }
  }
Exemplo n.º 7
0
  public void guardarCambiosGrupo() {

    JSONArray lista = new JSONArray();

    for (int i = 0; i < listaTecnicosGrupo.size(); i++) {
      lista.put(listaTecnicosGrupo.get(i).getMail());
    }

    JSONObject respuesta =
        new IGrupo()
            .modificiarGrupo(
                sesion.getTokenId(),
                grupoSeleccionado,
                nuevoNombreGrupo,
                lista,
                parsearMail(nuevoAdministrador));
    try {
      FacesMessage msg;
      if (respuesta.getInt("status") == 2) {
        msg = new FacesMessage("Grupo modificado con exito", "");
        listarGrupos();
      } else msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error al modificar grupo.", "");

      FacesContext.getCurrentInstance().addMessage(null, msg);

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 8
0
 public static Foo fromString(String str) {
   try {
     JSONObject jsonObj = new JSONObject(str);
     return new Foo(jsonObj.getInt("i"), jsonObj.getString("s"));
   } catch (JSONException e) {
     throw new RuntimeException("failed to construct JSONObject for toString", e);
   }
 }
Exemplo n.º 9
0
  @Test
  public void testCreatePreference() throws JSONException {

    JSONObject createPreferenceResult =
        mp.createPreference(
            "{'items':[{'title':'Prueba','quantity':1,'currency_id':'ARS','unit_price':10.5}]}");

    assertEquals(createPreferenceResult.getInt("status"), 201);

    JSONObject createdPreference =
        (JSONObject) createPreferenceResult.getJSONObject("response").getJSONArray("items").get(0);

    assertEquals(createdPreference.getString("title"), "Prueba");
    assertEquals(createdPreference.getInt("quantity"), 1);
    assertEquals(createdPreference.getString("currency_id"), "ARS");
    assertEquals(createdPreference.getDouble("unit_price"), 10, 5d);
  }
Exemplo n.º 10
0
 /** @return the geoNameId. */
 public int getGeoNameId() {
   try {
     return data.getInt(ToponymProperty.geonameId.name());
   } catch (JSONException e) {
     throw new IllegalStateException(
         String.format("Unable to parse %s form %s", ToponymProperty.geonameId, data));
   }
 }
Exemplo n.º 11
0
  public void verifyClusterSchedulerFifo(JSONObject json) throws JSONException, Exception {
    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject info = json.getJSONObject("scheduler");
    assertEquals("incorrect number of elements", 1, info.length());
    info = info.getJSONObject("schedulerInfo");
    assertEquals("incorrect number of elements", 11, info.length());

    verifyClusterSchedulerFifoGeneric(
        info.getString("type"),
        info.getString("qstate"),
        (float) info.getDouble("capacity"),
        (float) info.getDouble("usedCapacity"),
        info.getInt("minQueueMemoryCapacity"),
        info.getInt("maxQueueMemoryCapacity"),
        info.getInt("numNodes"),
        info.getInt("usedNodeCapacity"),
        info.getInt("availNodeCapacity"),
        info.getInt("totalNodeCapacity"),
        info.getInt("numContainers"));
  }
Exemplo n.º 12
0
 @Test
 public void invokeMethodWithIntParamsWithString() throws Exception {
   JSONObject o = new JSONObject();
   JSONArray params = new JSONArray(Arrays.asList("1", "2"));
   o.put("params", params);
   JSONObject jo =
       r.path(MBeanServerSetup.TESTDOMAIN_NAME_TEST_BEAN + "/ops/methodWithParams")
           .type("application/json")
           .post(JSONObject.class, o);
   assertEquals("No correct return value " + jo, 0, jo.getInt("return"));
 }
Exemplo n.º 13
0
 /** @return the elevation in meter. */
 public Integer getElevation() {
   try {
     if (data.has(ToponymProperty.elevation.name())) {
       return data.getInt(ToponymProperty.elevation.name());
     } else {
       return null;
     }
   } catch (JSONException e) {
     throw new IllegalStateException(
         String.format("Unable to parse %s form %s", ToponymProperty.elevation, data));
   }
 }
Exemplo n.º 14
0
  @Path("/create")
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response createResponse(String input) throws Exception {

    JSONObject inputObj = new JSONObject(input);
    Datastore ds = MongoConnection.getServer();
    List<ClientObject> clientObjects =
        ds.createQuery(ClientObject.class)
            .filter("client_bs_obj.device_id =", inputObj.getString("client_bs_obj.device_id"))
            .asList();

    ClientObject clientObject = clientObjects.get(0);
    Map<Integer, ObjInstance> objInstanceMap =
        clientObject.getObjectMap().get(inputObj.getInt("ObjectId")).getObjInstanceMap();
    Map<Integer, Resource> resourceMap =
        objInstanceMap.get(inputObj.getInt("ObjectInsId")).getResourceMap();
    ObjInstance objInstance = new ObjInstance();
    objInstance.setObjInstance_id(inputObj.getInt("ObjectInsId") + 1);
    Resource resource = new Resource();
    resource.setRecourse_id(0);
    resource.setName(inputObj.getString("value"));
    Map<Integer, Resource> resourceMapNew = objInstance.getResourceMap();
    resourceMapNew.put(0, resource);
    objInstanceMap.put(objInstance.getObjInstance_id(), objInstance);

    // Map<Integer,Resource> resourceMap = objInstanceMap.get(ObjectInsId).getResourceMap();

    ds.save(clientObject);

    CountDownLatch signalRead =
        Info.getCountDownMessage(inputObj.getString("client_bs_obj.device_id"));
    signalRead.countDown();

    return Response.status(200).entity(inputObj.getString("message")).build();
  }
Exemplo n.º 15
0
  @Override
  protected Referenceable createAccInfoRef(JSONObject dbConnObj, JSONObject dbInfoObj)
      throws Exception {
    String typeName = dbConnObj.getString("dbType").toLowerCase();
    String connName = dbConnObj.getString("name");
    String qualifiedName = DxtStoreUtil.formatQualifiedName(typeName, connName);

    Referenceable generalAccInfoRef =
        DxtStoreUtil.createDxtRef(
            DxtDataTypes.GENERAL_ACCINFO.getValue(), qualifiedName, DxtConstant.ACCINFO_TRAIT);
    generalAccInfoRef.set("name", connName);
    generalAccInfoRef.set("host", dbInfoObj.getString("host"));
    generalAccInfoRef.set("port", dbInfoObj.getInt("port"));

    return generalAccInfoRef;
  }
Exemplo n.º 16
0
 @Test
 public void getTaskmanagers() {
   try {
     String json = getFromHTTP("http://localhost:" + port + "/taskmanagers/");
     JSONObject parsed = new JSONObject(json);
     JSONArray taskManagers = parsed.getJSONArray("taskmanagers");
     Assert.assertNotNull(taskManagers);
     Assert.assertEquals(cluster.numTaskManagers(), taskManagers.length());
     JSONObject taskManager = taskManagers.getJSONObject(0);
     Assert.assertNotNull(taskManager);
     Assert.assertEquals(4, taskManager.getInt("freeSlots"));
   } catch (Throwable e) {
     e.printStackTrace();
     Assert.fail(e.getMessage());
   }
 }
Exemplo n.º 17
0
  @POST
  @Path("update")
  @Consumes(MediaType.APPLICATION_JSON)
  public String updateUserData(String json)
      throws JSONException, IOException, NonexistentEntityException, RollbackFailureException,
          Exception {
    JSONObject jObj = new JSONObject(json);
    try {
      int userId = jObj.getInt("userID");
      String email = jObj.getString("email");
      String password = jObj.getString("password");

      String middleName = jObj.optString("middle_name");
      String lastName = jObj.optString("last_name");
      String street = jObj.optString("street");
      String houseNumber = jObj.optString("house_number");
      String postalCode = jObj.optString("postal_code");
      String city = jObj.optString("city");
      String country = jObj.optString("country");

      Account account = dbManager.findById(Account.class, userId);
      account.setUserName(email);
      account.setPassword(password);
      User user = account.getUser();
      user.setCity(city);
      user.setCountry(country);
      user.setHouseNumber(houseNumber);
      user.setLastName(lastName);
      user.setPostalCode(postalCode);
      user.setStreet(street);

      if (password != null && !password.isEmpty()) {
        dbManager.save(account);
      }
      dbManager.save(user);

    } catch (Exception ex) {
      Logger.getLogger(ChangeAccount.class.getName()).log(Level.SEVERE, null, ex);
      return jObj.put("result", true).toString();
    }
    jObj = new JSONObject();

    return jObj.put("result", true).toString();
  }
Exemplo n.º 18
0
  /**
   * Get Access Token for API use
   *
   * @throws JSONException
   */
  public String getAccessToken() throws JSONException, Exception {
    if (null != this.ll_access_token) {
      return this.ll_access_token;
    }

    HashMap<String, Object> appClientValues = new HashMap<String, Object>();
    appClientValues.put("grant_type", "client_credentials");
    appClientValues.put("client_id", this.client_id);
    appClientValues.put("client_secret", this.client_secret);

    String appClientValuesQuery = this.buildQuery(appClientValues);

    JSONObject access_data =
        RestClient.post("/oauth/token", appClientValuesQuery, RestClient.MIME_FORM);

    if (access_data.getInt("status") == 200) {
      this.access_data = access_data.getJSONObject("response");
      return this.access_data.optString("access_token");
    } else {
      throw new Exception(access_data.toString());
    }
  }
Exemplo n.º 19
0
 public void verifyClusterMetricsJSON(JSONObject json) throws JSONException, Exception {
   assertEquals("incorrect number of elements", 1, json.length());
   JSONObject clusterinfo = json.getJSONObject("clusterMetrics");
   assertEquals("incorrect number of elements", 19, clusterinfo.length());
   verifyClusterMetrics(
       clusterinfo.getInt("appsSubmitted"),
       clusterinfo.getInt("appsCompleted"),
       clusterinfo.getInt("reservedMB"),
       clusterinfo.getInt("availableMB"),
       clusterinfo.getInt("allocatedMB"),
       clusterinfo.getInt("containersAllocated"),
       clusterinfo.getInt("totalMB"),
       clusterinfo.getInt("totalNodes"),
       clusterinfo.getInt("lostNodes"),
       clusterinfo.getInt("unhealthyNodes"),
       clusterinfo.getInt("decommissionedNodes"),
       clusterinfo.getInt("rebootedNodes"),
       clusterinfo.getInt("activeNodes"));
 }
Exemplo n.º 20
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());
  }
Exemplo n.º 21
0
 private CSVEntry processResponses(PersistenceManager pm, List<Response> responseJDOs) {
   CSVEntry entry = CSVCache.getInstance().getCSV(csvId);
   if (entry == null) {
     entry =
         new CSVEntry(
             "Response Identifier;Timestamp;Item Identifier;Response Item Identifier; Account; "
                 + "Image Url; Video Url; Width; Height; Latitude; Longitude; Audio Url;Text; Value \n",
             CSVEntry.BUILDING_STATUS);
   }
   String csv = entry.getCSV();
   for (Response responseJDO : responseJDOs) {
     String value = responseJDO.getResponseValue();
     String imageUrl = "";
     String audioUrl = "";
     String videoUrl = "";
     String width = "";
     String height = "";
     String text = "";
     String valueString = "";
     String lat = responseJDO.getLat() == null ? "" : "" + responseJDO.getLat().doubleValue();
     String lng = responseJDO.getLng() == null ? "" : "" + responseJDO.getLng().doubleValue();
     try {
       org.codehaus.jettison.json.JSONObject json =
           new org.codehaus.jettison.json.JSONObject(value);
       if (json.has("imageUrl")) imageUrl = json.getString("imageUrl");
       if (json.has("audioUrl")) audioUrl = json.getString("audioUrl");
       if (json.has("videoUrl")) videoUrl = json.getString("videoUrl");
       if (json.has("width")) width = "" + json.getInt("width");
       if (json.has("height")) height = "" + json.getInt("height");
       if (json.has("text")) text = json.getString("text");
       if (json.has("value")) valueString = json.getString("value");
     } catch (JSONException e) {
       e.printStackTrace();
     }
     //
     // {"imageUrl":"http:\/\/streetlearn.appspot.com\/\/uploadService\/2288002\/2:113116978440346588314\/image1537716519.jpg","width":3264,"height":1840}
     //            {"answer":"3","isCorrect":true}
     csv +=
         responseJDO.getResponseId()
             + ";"
             + responseJDO.getTimestamp()
             + ";"
             + responseJDO.getGeneralItemId()
             + ";"
             + responseJDO.getResponseItemId()
             + ";"
             + responseJDO.getUserEmail()
             + ";"
             + imageUrl
             + ";"
             + videoUrl
             + ";"
             + width
             + ";"
             + height
             + ";"
             + lat
             + ";"
             + lng
             + ";"
             + audioUrl
             + ";"
             + text
             + ";"
             + valueString
             + "\n";
   }
   entry.setCSV(csv);
   return entry;
 }