public JsonArray getPerfResults(String perfResults) {
    DBCollection coll = db.getCollection("performance");
    BasicDBObject query = new BasicDBObject();
    BasicDBObject removeId = new BasicDBObject("_id", 0);

    query.put("name", perfResults);

    DBCursor cursor = coll.find(query, removeId);
    JsonObjectBuilder objBuild = Json.createObjectBuilder();
    JsonArrayBuilder arrBuild = Json.createArrayBuilder();
    JsonObject json = objBuild.build();

    while (cursor.hasNext()) {
      BasicDBObject found = (BasicDBObject) cursor.next();
      LOG.info("Found Performance Results: " + found.toString());
      json = Json.createReader(new StringReader(found.toString())).readObject();

      arrBuild.add(json);
    }

    LOG.info(
        "----------------------------------- ARR BUILD -------------------------------------------------\n"
            + arrBuild.build().toString());

    return arrBuild.build();
  }
  public JsonArray addPerfResults(String perfResults) {
    DBCollection coll = db.getCollection("performance");
    BasicDBObject newPerfResults = (BasicDBObject) JSON.parse(perfResults);
    newPerfResults.append("_id", newPerfResults.getString("name"));

    BasicDBObject query = new BasicDBObject();
    query.append("name", newPerfResults.getString("name"));

    BasicDBObject removeId = new BasicDBObject("_id", 0);
    DBCursor cursor = coll.find(query, removeId);

    JsonObjectBuilder objBuild = Json.createObjectBuilder();
    JsonArrayBuilder arrBuild = Json.createArrayBuilder();
    JsonObject json = objBuild.build();

    if (cursor.count() > 0) {
      LOG.info("Performance Results Found: ");
      BasicDBObject found = (BasicDBObject) cursor.next();
      json = Json.createReader(new StringReader(found.toString())).readObject();
      arrBuild.add(json);
    } else {
      LOG.info("New Performance Results Created: " + coll.insert(newPerfResults));
      json = Json.createReader(new StringReader(newPerfResults.toString())).readObject();
      arrBuild.add(json);
    }

    LOG.info(
        "----------------------------------- ARR BUILD -------------------------------------------------\n"
            + arrBuild.build().toString());

    return arrBuild.build();
  }
Ejemplo n.º 3
0
 private JsonArray getDocumentJsonArray() {
   final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
   for (final JsonObject document : documents) {
     arrayBuilder.add(document);
   }
   return arrayBuilder.build();
 }
 protected JsonArray toJson(IdentitySet<InstanceKey> set) {
   JsonArrayBuilder builder = Json.createArrayBuilder();
   for (InstanceKey inst : set) {
     builder.add(toJson(inst));
   }
   return builder.build();
 }
 protected JsonArray toJson(Set<PointerKey> set) {
   JsonArrayBuilder builder = Json.createArrayBuilder();
   for (PointerKey ptr : set) {
     builder.add(toJson(ptr));
   }
   return builder.build();
 }
Ejemplo n.º 6
0
 @GET
 public JsonArray all(@Context UriInfo info) {
   JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
   List<String> cacheNames = discoverer.cacheNames();
   cacheNames.stream().map(n -> createCacheLinks(info, n)).forEach(arrayBuilder::add);
   return arrayBuilder.build();
 }
Ejemplo n.º 7
0
 /** {@inheritDoc} */
 @Override
 public JsonObject toJSON(Properties properties) {
   JsonObjectBuilder json =
       NullAwareJsonObjectBuilder.wrap(this.jsonFactory.createObjectBuilder());
   if (PropertiesUtil.getBoolean(properties, "hardware.usbDevices.name")) {
     json.add("name", getName());
   }
   if (PropertiesUtil.getBoolean(properties, "hardware.usbDevices.vendor")) {
     json.add("vendor", getVendor());
   }
   if (PropertiesUtil.getBoolean(properties, "hardware.usbDevices.vendorId")) {
     json.add("vendorId", getVendorId());
   }
   if (PropertiesUtil.getBoolean(properties, "hardware.usbDevices.productId")) {
     json.add("productId", getProductId());
   }
   if (PropertiesUtil.getBoolean(properties, "hardware.usbDevices.serialNumber")) {
     json.add("serialNumber", getSerialNumber());
   }
   if (PropertiesUtil.getBoolean(properties, "hardware.usbDevices.connectedDevices")
       && PropertiesUtil.getBoolean(properties, "hardware.usbDevices.tree")) {
     JsonArrayBuilder usbDeviceArrayBuilder = this.jsonFactory.createArrayBuilder();
     for (UsbDevice usbDevice : getConnectedDevices()) {
       usbDeviceArrayBuilder.add(usbDevice.toJSON());
     }
     json.add("connectedDevices", usbDeviceArrayBuilder.build());
   }
   return json.build();
 }
Ejemplo n.º 8
0
 /** @return names of all known state machines */
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public JsonArray all() {
   JsonArrayBuilder builder = Json.createArrayBuilder();
   this.dm.stateMachineNames().forEach(builder::add);
   return builder.build();
 }
Ejemplo n.º 9
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

      emf = Persistence.createEntityManagerFactory("image-sharing-servicePU");
      em = emf.createEntityManager();

      JsonArrayBuilder builder = Json.createArrayBuilder();

      for (Images i : (List<Images>) em.createNamedQuery("Images.findAll").getResultList()) {
        String imagePath = i.getPath();

        builder.add(
            Json.createObjectBuilder()
                .add("path", imagePath)
                .add("id", i.getId())
                .add("rating", "1"));
      }

      JsonArray arr = builder.build();

      out.println(arr);

    } catch (Exception e) {
      out.println(e);
    } finally {
      em.close();
      emf.close();
      out.close();
    }
  }
Ejemplo n.º 10
0
  private static String retrieveOFileNameRemote(String[] cmdArray) {
    JsonArrayBuilder jab = Json.createArrayBuilder();
    for (String s : cmdArray) {
      jab.add(s);
    }

    // add jobId for server side database
    // jab.add(OCSSW.getJobId());
    JsonArray remoteCmdArray = jab.build();

    OCSSWClient ocsswClient = new OCSSWClient();
    WebTarget target = ocsswClient.getOcsswWebTarget();
    final Response response =
        target
            .path("ocssw")
            .path("computeNextLevelFileName")
            .path(OCSSW.getJobId())
            .request(MediaType.APPLICATION_JSON_TYPE)
            .post(Entity.entity(remoteCmdArray, MediaType.APPLICATION_JSON_TYPE));

    String ofileName =
        target
            .path("ocssw")
            .path("retrieveNextLevelFileName")
            .path(OCSSW.getJobId())
            .request(MediaType.TEXT_PLAIN)
            .get(String.class);
    if (ofileName != null) {
      return ofileName;
    } else {
      return "output";
    }
  }
Ejemplo n.º 11
0
 @POST
 @Consumes({"application/json"})
 @Produces("text/plain")
 /** Запись или обновление данных о пользователе с передачей их JSON-потоком */
 public String addUserJson(
     @QueryParam("token") String token,
     JsonObject userData,
     @PathParam("schema") String schemaName) {
   // Проверка клиента
   UserLogon logon = usersController.getUserLogon(token);
   if (logon == null) {
     return "Unknown token: " + token;
   }
   // Проверка схемы
   int schemaID = 0;
   ConnectionSchema connectionSchema = null;
   try {
     connectionSchema = cg.getConnectionSchemaByAlias(schemaName);
     schemaID = connectionSchema.getId();
   } catch (CarabiException ex) {
     return "Unknown schema: " + schemaName;
   } catch (Exception ex) {
     Logger.getLogger(UsersAdmin.class.getName()).log(Level.SEVERE, null, ex);
     return ex.getMessage();
   }
   String login = userData.getString("login");
   JsonObjectBuilder userDataNew = Utls.jsonObjectToBuilder(userData);
   // если редактируемый пользователь с таким логином существует -- проверка, что нет коллизии
   // между базами
   long userID = usersPercistence.getUserID(login);
   boolean userIsNew = userID == -1;
   if (!userIsNew) {
     try {
       CarabiUser user = usersController.findUser(login);
       // пользователь из новой БД должен иметь такой же пароль, чтобы быть принятым автоматически
       if (!user.getDefaultSchema().getId().equals(schemaID)
           && !user.getAllowedSchemas().contains(connectionSchema)
           && !user.getPassword().equals(userData.getString("password"))) {
         return "user " + login + " already registered with another database";
       }
       userDataNew.add("id", "" + userID);
     } catch (CarabiException ex) {
       Logger.getLogger(UsersAdmin.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
   userDataNew.add("defaultSchemaId", schemaID);
   JsonArrayBuilder allowedSchemaIds = Json.createArrayBuilder();
   allowedSchemaIds.add(schemaID);
   userDataNew.add("allowedSchemaIds", allowedSchemaIds.build());
   try {
     return admin.saveUser(logon, userDataNew.build(), userIsNew, true).toString();
   } catch (Exception ex) {
     Logger.getLogger(UsersAdmin.class.getName()).log(Level.SEVERE, null, ex);
     return ex.getMessage();
   }
 }
Ejemplo n.º 12
0
  public static JsonArray arrayToJson(Collection<?> array) {

    JsonArrayBuilder json = Json.createArrayBuilder();

    for (Object object : array) {
      json.add(objectToJson(object));
    }

    return json.build();
  }
Ejemplo n.º 13
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.setCharacterEncoding("UTF-8");
    HttpSession user = req.getSession();
    PrintWriter out = resp.getWriter();
    SpejdResultAnalyser result = null;
    JsonObject response;

    JsonReader jsonReader =
        Json.createReader(new InputStreamReader(req.getInputStream(), StandardCharsets.ISO_8859_1));
    JsonObject jsonObject = jsonReader.readObject();
    jsonReader.close();
    System.out.println("REQUEST");
    System.out.println(jsonObject);
    String originalText = jsonObject.getString("text");
    int space = jsonObject.getInt("space");

    String xml = getXml(originalText, user.getId());
    try {
      result = new SpejdResultAnalyser(xml.replace("SYSTEM \"xcesAnaIPI.dtd\"", ""));
    } catch (ParserConfigurationException | SAXException e) {
      out.println(e.toString());
    }

    assert result != null;
    /** do analysis of xml spejd result */
    SubstantivePairs pairs = result.doAnalysis().makePair(space);

    /**
     * create json response { text: ... xml: ... pairs: [ { subst1: ... subst2: ... quantity: ... },
     * ...] }
     */
    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
    for (SubstantivePair pair : pairs) {
      arrayBuilder.add(
          Json.createObjectBuilder()
              .add("subst1", pair.getSubst1())
              .add("subst2", pair.getSubst2())
              .add("quantity", pair.getQuantity()));
    }

    Charset.forName("UTF-8").encode(originalText);
    JsonArray array = arrayBuilder.build();
    response =
        Json.createObjectBuilder()
            .add("text", originalText)
            .add("xml", xml)
            .add("pairs", array)
            .build();
    System.out.println("RESPONSE");
    System.out.println(response);
    out.print(response);
  }
  @Override
  public Response getSharedLocations(Long userId) throws ServiceException {
    JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
    List<SharedLocation> locations = shareLocationService.getSharedLocations(userId);
    for (SharedLocation l : locations) {
      JsonObjectBuilder jsonUserObjectBuilder = createJsonSharedLocation(l);
      jsonArrayBuilder.add(jsonUserObjectBuilder);
    }

    return Response.ok(jsonArrayBuilder.build().toString()).build();
  }
Ejemplo n.º 15
0
  public JsonObject toJson() {
    JsonObjectBuilder builder =
        Json.createObjectBuilder().add("success", success).add("insertedSize", insertedSize);

    if (!errors.isEmpty()) {
      JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
      for (WriteError writeError : errors) {
        arrayBuilder.add(writeError.toJson());
      }
      builder.add("errors", arrayBuilder.build());
    }

    return builder.build();
  }
Ejemplo n.º 16
0
 @GET
 public JsonArray getBooks() {
   final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
   final Set<Map.Entry<Long, JsonObject>> entries = BookResource.memoryBase.entrySet();
   final Iterator<Entry<Long, JsonObject>> iterator = entries.iterator();
   while (iterator.hasNext()) {
     final Entry<Long, JsonObject> cursor = iterator.next();
     Long key = cursor.getKey();
     JsonObject value = cursor.getValue();
     BookResource.LOGGER.debug(key);
     arrayBuilder.add(value);
   }
   JsonArray result = arrayBuilder.build();
   return result;
 }
Ejemplo n.º 17
0
 /**
  * Returns a JsonObject representing the object in BBDD.
  *
  * @return
  */
 public JsonObject toJSON() {
   SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
   JsonArrayBuilder builder = Json.createArrayBuilder();
   if (tags != null) {
     for (String tag : tags) {
       builder = builder.add(tag);
     }
   }
   return Json.createObjectBuilder()
       .add("id", recipeId)
       .add("title", recipeTitle)
       .add("recipe", recipe != null ? recipe : "")
       .add("date", recipeDate != null ? sdf.format(recipeDate) : "")
       .add("update", recipeUpdate != null ? sdf.format(recipeUpdate) : "")
       .add("origin", recipeOrigin != null ? recipeOrigin : "")
       .add("shareId", getRecipeShareId() != null ? getRecipeShareId() : "")
       .add("tags", builder.build())
       .build();
 }
  @GET
  @Path("/products/{id}")
  @Produces("application/json")
  public String getProductById(@PathParam("id") int productId) throws SQLException {
    // TODO return proper representation object
    // throw new UnsupportedOperationException();

    Connection conn = getConnection();
    if (conn == null) {
      // return "database connection error";
    }

    String query = "select * from product where productid=" + productId;
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(query);

    while (rs.next()) {
      Product product =
          new Product(
              rs.getInt("productid"),
              rs.getString("name"),
              rs.getString("description"),
              rs.getInt("quantity"));
      productList.add(product);

      json =
          Json.createObjectBuilder()
              .add("productID", rs.getInt("productID"))
              .add("name", rs.getString("name"))
              .add("description", rs.getString("description"))
              .add("quantity", rs.getInt("quantity"));
      productJsonArray.add(json);
    }

    String resultString = productJsonArray.build().toString();
    conn.close();
    return resultString;
  }
Ejemplo n.º 19
0
 public static int navigateTree(JsonValue tree, String skip) {
   int ret = 0;
   switch (tree.getValueType()) {
     case OBJECT:
       // System.out.println("OBJECT");
       JsonArrayBuilder dirtyResult = Json.createArrayBuilder();
       JsonObject object = (JsonObject) tree;
       for (String name : object.keySet()) {
         if (object.get(name).getValueType() == JsonValue.ValueType.STRING
             && object.getString(name).equals(skip)) {
           return 0;
         }
         dirtyResult.add(object.get(name));
       }
       ret = ret + navigateTree(dirtyResult.build(), skip);
       break;
     case ARRAY:
       // System.out.println("ARRAY");
       JsonArray array = (JsonArray) tree;
       for (JsonValue val : array) ret = ret + navigateTree(val, skip);
       break;
     case STRING:
       JsonString st = (JsonString) tree;
       // System.out.println("STRING " + st.getString());
       break;
     case NUMBER:
       JsonNumber num = (JsonNumber) tree;
       return num.intValue();
     case TRUE:
     case FALSE:
     case NULL:
       // System.out.println(tree.getValueType().toString());
       break;
   }
   return ret;
 }
Ejemplo n.º 20
0
 /**
  * Tranfort an array of bytes to a json array
  *
  * @param array array of bytes
  * @return Json array with the byte
  */
 public static JsonArray toJson(Byte[] array) {
   JsonArrayBuilder jsonArray = Json.createArrayBuilder();
   for (Byte str : array) jsonArray.add(str);
   return jsonArray.build();
 }
Ejemplo n.º 21
0
 /**
  * Transfort a collection of strings into a Json array
  *
  * @param collection list to "jsonify"
  * @return Json array containing to given collection
  */
 public static JsonArray toJson(Collection<String> collection) {
   JsonArrayBuilder jsonArray = Json.createArrayBuilder();
   for (String str : collection) jsonArray.add(str);
   return jsonArray.build();
 }