Beispiel #1
0
  @Test
  public void testTaskIdCountersDefault() throws JSONException, Exception {
    WebResource r = resource();
    Map<JobId, Job> jobsMap = appContext.getAllJobs();
    for (JobId id : jobsMap.keySet()) {
      String jobId = MRApps.toString(id);
      for (Task task : jobsMap.get(id).getTasks().values()) {

        String tid = MRApps.toString(task.getID());
        ClientResponse response =
            r.path("ws")
                .path("v1")
                .path("history")
                .path("mapreduce")
                .path("jobs")
                .path(jobId)
                .path("tasks")
                .path(tid)
                .path("counters")
                .get(ClientResponse.class);
        assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
        JSONObject json = response.getEntity(JSONObject.class);
        assertEquals("incorrect number of elements", 1, json.length());
        JSONObject info = json.getJSONObject("jobTaskCounters");
        verifyHsJobTaskCounters(info, task);
      }
    }
  }
 private boolean hasOrAndOperator(JSONObject jsonCriteria) throws JSONException {
   if (!jsonCriteria.has(OPERATOR_KEY)) {
     return mainOperatorIsAnd;
   }
   return OPERATOR_OR.equals(jsonCriteria.get(OPERATOR_KEY))
       || OPERATOR_AND.equals(jsonCriteria.get(OPERATOR_KEY));
 }
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  public Response saveListItem(InputStream incomingData) {
    StringBuilder listBuilder = new StringBuilder();
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
      String line = null;
      while ((line = in.readLine()) != null) {
        listBuilder.append(line);
      }
    } catch (Exception e) {
      System.out.println("Error Parsing: - ");
    }

    try {
      JSONObject json = new JSONObject(listBuilder.toString());
      Iterator<String> iterator = json.keys();
      if (list == null) {
        list = new ArrayList<ListItem>();
      }
      ListItem item =
          new ListItem(
              (String) json.get(iterator.next()),
              (String) json.get(iterator.next()),
              (Boolean) json.get(iterator.next()));
      list.add(item);
    } catch (JSONException e) {
      e.printStackTrace();
      return Response.status(500).entity(listBuilder.toString()).build();
    }
    // return HTTP response 200 in case of success
    return Response.status(200).entity(listBuilder.toString()).build();
  }
Beispiel #4
0
  /**
   * Deletes a file.
   *
   * @param id File ID
   * @return Response
   * @throws JSONException
   */
  @DELETE
  @Path("{id: [a-z0-9\\-]+}")
  @Produces(MediaType.APPLICATION_JSON)
  public Response delete(@PathParam("id") String id) throws JSONException {
    if (!authenticate()) {
      throw new ForbiddenClientException();
    }

    // Get the file
    FileDao fileDao = new FileDao();
    DocumentDao documentDao = new DocumentDao();
    File file;
    try {
      file = fileDao.getFile(id);
      documentDao.getDocument(file.getDocumentId(), principal.getId());
    } catch (NoResultException e) {
      throw new ClientException("FileNotFound", MessageFormat.format("File not found: {0}", id));
    }

    // Delete the file
    fileDao.delete(file.getId());

    // Raise a new file deleted event
    FileDeletedAsyncEvent fileDeletedAsyncEvent = new FileDeletedAsyncEvent();
    fileDeletedAsyncEvent.setFile(file);
    AppContext.getInstance().getAsyncEventBus().post(fileDeletedAsyncEvent);

    // Always return ok
    JSONObject response = new JSONObject();
    response.put("status", "ok");
    return Response.ok().entity(response).build();
  }
  @Test(dependsOnMethods = "testSubmit")
  public void testGetTypeNames() throws Exception {
    WebResource resource = service.path("api/atlas/types");

    ClientResponse clientResponse =
        resource
            .accept(Servlets.JSON_MEDIA_TYPE)
            .type(Servlets.JSON_MEDIA_TYPE)
            .method(HttpMethod.GET, ClientResponse.class);
    assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode());

    String responseAsString = clientResponse.getEntity(String.class);
    Assert.assertNotNull(responseAsString);

    JSONObject response = new JSONObject(responseAsString);
    Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));

    final JSONArray list = response.getJSONArray(AtlasClient.RESULTS);
    Assert.assertNotNull(list);

    // Verify that primitive and core types are not returned
    String typesString = list.join(" ");
    Assert.assertFalse(typesString.contains(" \"__IdType\" "));
    Assert.assertFalse(typesString.contains(" \"string\" "));
  }
  @Test
  public void testNodeAppsState() throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    addAppContainers(app);
    MockApp app2 = new MockApp("foo", 1234, 2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    HashMap<String, String> hash2 = addAppContainers(app2);
    app2.setState(ApplicationState.RUNNING);

    ClientResponse response =
        r.path("ws")
            .path("v1")
            .path("node")
            .path("apps")
            .queryParam("state", ApplicationState.RUNNING.toString())
            .accept(MediaType.APPLICATION_JSON)
            .get(ClientResponse.class);

    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);

    JSONObject info = json.getJSONObject("apps");
    assertEquals("incorrect number of elements", 1, info.length());
    JSONArray appInfo = info.getJSONArray("app");
    assertEquals("incorrect number of elements", 1, appInfo.length());
    verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2);
  }
 /**
  * Creates a topic model from a JSON value.
  *
  * <p>Both topic serialization formats are supported: 1) canonic format -- contains entire topic
  * models. 2) compact format -- contains the topic value only (simple or composite).
  */
 private TopicModel createTopicModel(String childTypeUri, Object value) {
   if (value instanceof JSONObject) {
     JSONObject val = (JSONObject) value;
     // we detect the canonic format by checking for a mandatory topic property
     // ### TODO: "type_uri" should not be regarded mandatory. It would simplify update requests.
     // ### Can we use another heuristic for detection: "value" exists OR "composite" exists?
     if (val.has("type_uri")) {
       // canonic format
       return new TopicModel(val);
     } else {
       // compact format (composite topic)
       return new TopicModel(childTypeUri, new CompositeValueModel(val));
     }
   } else {
     // compact format (simple topic or topic reference)
     if (value instanceof String) {
       String val = (String) value;
       if (val.startsWith(REF_ID_PREFIX)) {
         return new TopicReferenceModel(refTopicId(val)); // topic reference by-ID
       } else if (val.startsWith(REF_URI_PREFIX)) {
         return new TopicReferenceModel(refTopicUri(val)); // topic reference by-URI
       } else if (val.startsWith(DEL_PREFIX)) {
         return new TopicDeletionModel(delTopicId(val)); // topic deletion reference
       }
     }
     // compact format (simple topic)
     return new TopicModel(childTypeUri, new SimpleValue(value));
   }
 }
Beispiel #8
0
    private static JSONObject exec(String method, String uri, Object data, String contentType)
        throws JSONException {
      ClientResponse apiResult;
      JSONObject response = new JSONObject();

      try {
        apiResult =
            buildRequest(API_BASE_URL + uri, contentType)
                .method(method, ClientResponse.class, data);
        int apiHttpCode = apiResult.getStatus();

        response.put("status", apiHttpCode);

        String responseBody = apiResult.getEntity(String.class);

        response.put(
            "response",
            responseBody.indexOf("[") == 0
                ? new JSONArray(responseBody)
                : new JSONObject(responseBody));
      } catch (Exception e) {
        response.put("status", 500);
        response.put("error", e.getMessage());
      }

      return response;
    }
  /**
   * Metodo web para calculo da rota
   *
   * @param json
   * @return json
   * @throws JSONException
   * @throws IOException
   * @throws JsonMappingException
   * @throws JsonParseException
   */
  @POST
  @Path("/searchZipCode")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response zipFind(String json)
      throws JSONException, JsonParseException, JsonMappingException, IOException {
    RespostaWebService result = new RespostaWebService();
    Response response = null;
    try {
      final JSONObject jsonObj = new JSONObject(json);
      final ObjectMapper objectMapper = new ObjectMapper();
      final RequestFindZipCode request =
          objectMapper.readValue(jsonObj.toString(), RequestFindZipCode.class);

      searchZipBusiness.validZipCode(request.getCep());

      result = searchZipBusiness.tryToFindZipCode(request.getCep(), objectMapper);

      return Response.status(Response.Status.OK).entity(result).build();
    } catch (final BusinessException e) {
      response = new ExceptionMapperImpl().toResponse(e);
    } catch (Exception e) {
      response = new ExceptionMapperImpl().toResponse(e);
    }
    return response;
  }
  /**
   * Get the URL of the file to download. This has not been modified from the original version.
   *
   * <p>For more information, please see: <a href=
   * "https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-portal-help#features">
   * https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-
   * portal-help#features</a>
   *
   * <p>Original code can be accessed at: <a href=
   * "https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip">
   * https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip </a>
   *
   * @see #login(String, String)
   * @see org.collegeboard.scoredwnld.client.FileInfo
   * @author CollegeBoard
   * @param accessToken Access token obtained from {@link #login(String, String)}
   * @param filePath File to download
   * @return FileInfo descriptor of file to download
   */
  private FileInfo getFileUrlByToken(String accessToken, String filePath) {

    Client client = getClient();
    WebResource webResource =
        client.resource(
            scoredwnldUrlRoot + "/pascoredwnld/file?tok=" + accessToken + "&filename=" + filePath);
    ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
    if (response.getStatus() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    try {
      JSONObject json = new JSONObject(response.getEntity(String.class));
      FileInfo fileInfo = new FileInfo();
      fileInfo.setFileName(filePath);
      fileInfo.setFileUrl(String.valueOf(json.get("fileUrl")));
      return fileInfo;
    } catch (ClientHandlerException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    } catch (UniformInterfaceException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    } catch (JSONException e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    }

    return null;
  }
  /**
   * Login to the PAScoresDwnld site. This method has not been modified from the original published
   * by CollegeBoard.
   *
   * <p>For more information, please see: <a href=
   * "https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-portal-help#features">
   * https://collegereadiness.collegeboard.org/educators/higher-ed/reporting-
   * portal-help#features</a>
   *
   * <p>Original code can be accessed at: <a href=
   * "https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip">
   * https://collegereadiness.collegeboard.org/zip/pascoredwnld-java-sample.zip </a>
   *
   * @author CollegeBoard
   * @param username Username to login with
   * @param password Password to login with
   * @return Authentication token
   */
  private String login(String username, String password) {
    Client client = getClient();
    WebResource webResource = client.resource(scoredwnldUrlRoot + "/pascoredwnld/login");

    String input = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"};";

    ClientResponse response =
        webResource
            .accept("application/json")
            .type("application/json")
            .post(ClientResponse.class, input);

    if (response.getStatus() != 200) {
      throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    try {
      JSONObject json = new JSONObject(response.getEntity(String.class));
      return String.valueOf(json.get("token"));
    } catch (Exception e) {
      log("Error: " + e.getMessage());
      e.printStackTrace();
    }
    return "";
  }
  private JSONArray enrichProperties(String operatorClass, JSONArray properties)
      throws JSONException {
    JSONArray result = new JSONArray();
    for (int i = 0; i < properties.length(); i++) {
      JSONObject propJ = properties.getJSONObject(i);
      String propName = WordUtils.capitalize(propJ.getString("name"));
      String getPrefix =
          (propJ.getString("type").equals("boolean")
                  || propJ.getString("type").equals("java.lang.Boolean"))
              ? "is"
              : "get";
      String setPrefix = "set";
      OperatorClassInfo oci =
          getOperatorClassWithGetterSetter(
              operatorClass, setPrefix + propName, getPrefix + propName);
      if (oci == null) {
        result.put(propJ);
        continue;
      }
      MethodInfo setterInfo = oci.setMethods.get(setPrefix + propName);
      MethodInfo getterInfo = oci.getMethods.get(getPrefix + propName);

      if ((getterInfo != null && getterInfo.omitFromUI)
          || (setterInfo != null && setterInfo.omitFromUI)) {
        continue;
      }
      if (setterInfo != null) {
        addTagsToProperties(setterInfo, propJ);
      } else if (getterInfo != null) {
        addTagsToProperties(getterInfo, propJ);
      }
      result.put(propJ);
    }
    return result;
  }
  @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;
    }
  }
Beispiel #14
0
  public static void main(String[] args)
      throws SQLException, ClassNotFoundException, JSONException {
    PostgresDb db = new PostgresDb();
    // db.setUrl("jdbc:postgresql://localhost:5432/powaaim");

    try {
      Class.forName("org.postgresql.Driver");
      c = DriverManager.getConnection(db.getUrl(), db.getUser(), db.getPass());
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    st = c.createStatement();
    rs = st.executeQuery("SELECT id, name, externalshopid from shop where name='David_3'");
    System.out.println("id" + " " + "name" + " " + "externalshopid");
    c.close();
    obj = new JSONObject();

    while (rs.next()) {
      int id = rs.getInt("id");
      String externaId = rs.getString("externalshopid");
      String name = rs.getString("name");
      // System.out.println(id+ " " + " "+ name + " " +" "+ externaId);
      System.out.println();
      obj.put("id", id);
      obj.put("name", name);
      obj.put("externalshopid", externaId);
      System.out.print(obj);
    }
  }
Beispiel #15
0
  @Test
  public void testJSONObjectRepresentation() throws Exception {
    JSONObject object = new JSONObject();
    object.put("userid", 1234).put("username", CONTENT).put("email", "a@b").put("password", "****");

    _test(object, JSONObjectResource.class, MediaType.APPLICATION_JSON_TYPE);
  }
Beispiel #16
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;
    }
  }
  public void testNodeHelper(String path, String media) throws JSONException, Exception {
    WebResource r = resource();
    Application app = new MockApp(1);
    nmContext.getApplications().put(app.getAppId(), app);
    HashMap<String, String> hash = addAppContainers(app);
    Application app2 = new MockApp(2);
    nmContext.getApplications().put(app2.getAppId(), app2);
    HashMap<String, String> hash2 = addAppContainers(app2);

    ClientResponse response =
        r.path("ws").path("v1").path("node").path(path).accept(media).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    JSONObject info = json.getJSONObject("apps");
    assertEquals("incorrect number of elements", 1, info.length());
    JSONArray appInfo = info.getJSONArray("app");
    assertEquals("incorrect number of elements", 2, appInfo.length());
    String id = appInfo.getJSONObject(0).getString("id");
    if (id.matches(app.getAppId().toString())) {
      verifyNodeAppInfo(appInfo.getJSONObject(0), app, hash);
      verifyNodeAppInfo(appInfo.getJSONObject(1), app2, hash2);
    } else {
      verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2);
      verifyNodeAppInfo(appInfo.getJSONObject(1), app, hash);
    }
  }
  @SuppressWarnings("deprecation")
  @GET
  @Path("/list/")
  @Produces("application/json")
  public JSONArray doGet(@QueryParam("ids") String paramIds) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    String[] ids = paramIds.split(",");

    JSONArray jsonMovies = new JSONArray();
    for (String id : ids) {
      Entity movieEntity;
      JSONObject movieToAdd = null;
      Query query = new Query("Movie").addFilter("redboxid", Query.FilterOperator.EQUAL, id);
      List<Entity> movieEntitiesArray =
          datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
      if (movieEntitiesArray.size() == 0) {
        // need to get the movie from the Redbox and then add to db
        movieEntity = getRedboxInfoAndAdd();
      } else {
        movieEntity = movieEntitiesArray.get(0);
      }

      try {
        // todo put the movie properties here
        movieToAdd.put("title", movieEntity.getProperty("title"));
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return jsonMovies;
  }
 public static JSONObject toJSON(String msg, String level, Date date) throws JSONException {
   JSONObject jsonData = new JSONObject();
   jsonData.put("message", msg);
   jsonData.put("level", level);
   jsonData.put("date", date.getTime());
   return jsonData;
 }
Beispiel #20
0
  public void registrarUsuario(ActionEvent ae) {

    try {
      JSONObject respuesta =
          new IUsuario()
              .registrarUsuario(
                  sesion.getTokenId(),
                  sesion.getMail(),
                  nombre,
                  apellido,
                  telefono,
                  interno,
                  contrasena);

      String status = respuesta.getString("status");
      if (status.equals("2")) {
        sesion.setNuevoUsuario(false);
      }

      System.out.println(sesion.isNuevoUsuario());

      String mensaje = respuesta.getString("mensaje");
      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(mensaje, null));

    } catch (JSONException e) {
      e.printStackTrace();
      System.out.println("ERROR JSOOOOOOOOOOOON");
    }
  }
 private void appendProperty(
     JSONObject item, ISchemaType type, ISchemaProperty prop, ISerializationNode childNode) {
   Node n = (Node) childNode;
   ISchemaType propType = prop.getType();
   String propName = type.getQualifiedPropertyName(prop);
   try {
     if (prop.isAttribute()) {
       propName = "@" + propName;
       if (prop.getStructureType() == StructureType.MAP) {
         IMapSchemaProperty mapProp = (IMapSchemaProperty) prop;
         Object defaultValue = DefaultValueFactory.getDefaultValue(mapProp.getValueType());
         item.put(propName + "_1", defaultValue + "_1");
         item.put(propName + "_2", defaultValue + "_2");
       } else {
         Object defaultValue = DefaultValueFactory.getDefaultValue(propType);
         item.put(propName, defaultValue);
       }
     } else if (prop.getStructureType() == StructureType.COLLECTION) {
       item.put(propName, n.array);
     } else if (propType == null || propType.isComplex()) {
       item.put(propName, n.object);
     } else {
       Object defaultValue = DefaultValueFactory.getDefaultValue(prop);
       if (item != null) item.put(propName, defaultValue);
     }
   } catch (JSONException e) {
     e.printStackTrace();
   }
 }
Beispiel #22
0
  @Test
  public void shouldRetrieveDataFromXPathQuery() throws Exception {
    final String NODE_PATH = "/nodeForQuery";
    URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items" + NODE_PATH);
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON);

    String payload = "{ \"properties\": {\"jcr:primaryType\": \"nt:unstructured\" }}";
    connection.getOutputStream().write(payload.getBytes());

    assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_CREATED));
    connection.disconnect();

    URL queryUrl = new URL(SERVER_URL + "/mode%3arepository/default/query");
    connection = (HttpURLConnection) queryUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/jcr+xpath");

    payload = "//nodeForQuery";
    connection.getOutputStream().write(payload.getBytes());
    JSONObject queryResult = new JSONObject(getResponseFor(connection));
    JSONArray results = (JSONArray) queryResult.get("rows");

    assertThat(results.length(), is(1));

    JSONObject result = (JSONObject) results.get(0);
    assertThat(result, is(notNullValue()));
    assertThat((String) result.get("jcr:path"), is(NODE_PATH));
    assertThat((String) result.get("jcr:primaryType"), is("nt:unstructured"));
  }
  @Test(dependsOnMethods = "testSubmit")
  public void testGetDefinition() throws Exception {
    for (HierarchicalTypeDefinition typeDefinition : typeDefinitions) {
      System.out.println("typeName = " + typeDefinition.typeName);

      WebResource resource = service.path("api/atlas/types").path(typeDefinition.typeName);

      ClientResponse clientResponse =
          resource
              .accept(Servlets.JSON_MEDIA_TYPE)
              .type(Servlets.JSON_MEDIA_TYPE)
              .method(HttpMethod.GET, ClientResponse.class);
      assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode());

      String responseAsString = clientResponse.getEntity(String.class);
      Assert.assertNotNull(responseAsString);
      JSONObject response = new JSONObject(responseAsString);
      Assert.assertNotNull(response.get(AtlasClient.DEFINITION));
      Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));

      String typesJson = response.getString(AtlasClient.DEFINITION);
      final TypesDef typesDef = TypesSerialization.fromJson(typesJson);
      List<HierarchicalTypeDefinition<ClassType>> hierarchicalTypeDefinitions =
          typesDef.classTypesAsJavaList();
      for (HierarchicalTypeDefinition<ClassType> classType : hierarchicalTypeDefinitions) {
        for (AttributeDefinition attrDef : classType.attributeDefinitions) {
          if ("name".equals(attrDef.name)) {
            assertEquals(attrDef.isIndexable, true);
            assertEquals(attrDef.isUnique, true);
          }
        }
      }
    }
  }
Beispiel #24
0
  @Test
  public void shouldRespectQueryOffsetAndLimit() throws Exception {
    final String NODE_PATH = "nodeForOffsetAndLimitTest";

    createNode("/" + NODE_PATH, 1);
    createNode("/" + NODE_PATH, 2);
    createNode("/" + NODE_PATH, 3);
    createNode("/" + NODE_PATH, 4);

    URL queryUrl = new URL(SERVER_URL + "/mode%3arepository/default/query?offset=1&limit=2");
    HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/jcr+xpath");

    String payload = "//element(" + NODE_PATH + ") order by @foo";

    connection.getOutputStream().write(payload.getBytes());
    JSONObject queryResult = new JSONObject(getResponseFor(connection));
    JSONArray results = (JSONArray) queryResult.get("rows");

    assertThat(results.length(), is(2));

    JSONObject result = (JSONObject) results.get(0);
    assertThat(result, is(notNullValue()));
    assertThat((String) result.get("jcr:path"), is("/" + NODE_PATH + "[2]"));

    result = (JSONObject) results.get(1);
    assertThat(result, is(notNullValue()));
    assertThat((String) result.get("jcr:path"), is("/" + NODE_PATH + "[3]"));
  }
  @Test
  public void testSubmit() throws Exception {
    for (HierarchicalTypeDefinition typeDefinition : typeDefinitions) {
      String typesAsJSON = TypesSerialization.toJson(typeDefinition);
      System.out.println("typesAsJSON = " + typesAsJSON);

      WebResource resource = service.path("api/atlas/types");

      ClientResponse clientResponse =
          resource
              .accept(Servlets.JSON_MEDIA_TYPE)
              .type(Servlets.JSON_MEDIA_TYPE)
              .method(HttpMethod.POST, ClientResponse.class, typesAsJSON);
      assertEquals(clientResponse.getStatus(), Response.Status.CREATED.getStatusCode());

      String responseAsString = clientResponse.getEntity(String.class);
      Assert.assertNotNull(responseAsString);

      JSONObject response = new JSONObject(responseAsString);
      JSONArray typesAdded = response.getJSONArray(AtlasClient.TYPES);
      assertEquals(typesAdded.length(), 1);
      assertEquals(typesAdded.getJSONObject(0).getString("name"), typeDefinition.typeName);
      Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));
    }
  }
Beispiel #26
0
  // @FixFor( "MODE-886" )
  @Test
  public void shouldAllowJcrSql2Query() throws Exception {
    final String NODE_PATH = "nodeForJcrSql2QueryTest";

    createNode("/" + NODE_PATH, 1);

    createNode("/" + NODE_PATH + "/child", 1);
    createNode("/" + NODE_PATH + "/child", 2);
    createNode("/" + NODE_PATH + "/child", 3);
    createNode("/" + NODE_PATH + "/child", 4);

    URL queryUrl = new URL(SERVER_URL + "/mode%3arepository/default/query");
    HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();

    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/jcr+sql2");

    String payload = "SELECT * FROM [nt:unstructured] WHERE ISCHILDNODE('/" + NODE_PATH + "')";

    connection.getOutputStream().write(payload.getBytes());
    JSONObject queryResult = new JSONObject(getResponseFor(connection));
    JSONArray results = (JSONArray) queryResult.get("rows");

    assertThat(results.length(), is(4));
  }
 private boolean parseStructuredClause(JSONArray clauses, String hqlOperator)
     throws JSONException {
   boolean doOr = OPERATOR_OR.equals(hqlOperator);
   boolean doAnd = OPERATOR_AND.equals(hqlOperator);
   for (int i = 0; i < clauses.length(); i++) {
     final JSONObject clause = clauses.getJSONObject(i);
     if (clause.has(VALUE_KEY)
         && clause.get(VALUE_KEY) != null
         && clause.getString(VALUE_KEY).equals("")) {
       continue;
     }
     final boolean clauseResult = parseCriteria(clause);
     if (doOr && clauseResult) {
       return true;
     }
     if (doAnd && !clauseResult) {
       return false;
     }
   }
   if (doOr) {
     return false;
   } else if (doAnd) {
     return true;
   }
   return mainOperatorIsAnd;
 }
Beispiel #28
0
  private static void saveOpts(JSONObject obj) {
    String fileDir = System.getProperty("user.dir");
    File file = new File(fileDir, DATA_FILE);
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(file);
      Properties pro = new Properties();
      Iterator it = obj.keys();
      while (it.hasNext()) {
        String key = (String) it.next();
        String value = obj.getString(key);
        pro.setProperty(key, value);
      }
      pro.store(fos, " ");
      fos.close();
    } catch (Exception e) {

    } finally {
      try {
        if (null != fos) fos.close();
      } catch (IOException e) {

      }
    }
  }
Beispiel #29
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();
    }
  }
Beispiel #30
0
 @Test
 public void testTasksQueryReduce() throws JSONException, Exception {
   WebResource r = resource();
   Map<JobId, Job> jobsMap = appContext.getAllJobs();
   for (JobId id : jobsMap.keySet()) {
     String jobId = MRApps.toString(id);
     String type = "r";
     ClientResponse response =
         r.path("ws")
             .path("v1")
             .path("history")
             .path("mapreduce")
             .path("jobs")
             .path(jobId)
             .path("tasks")
             .queryParam("type", type)
             .accept(MediaType.APPLICATION_JSON)
             .get(ClientResponse.class);
     assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
     JSONObject json = response.getEntity(JSONObject.class);
     assertEquals("incorrect number of elements", 1, json.length());
     JSONObject tasks = json.getJSONObject("tasks");
     JSONArray arr = tasks.getJSONArray("task");
     assertEquals("incorrect number of elements", 1, arr.length());
     verifyHsTask(arr, jobsMap.get(id), type);
   }
 }