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();
  }
  public JsonArray updatePerfResults(String perfResults) {
    BasicDBObject doc = (BasicDBObject) JSON.parse(perfResults);
    doc.append("_id", doc.get("name"));

    DBCollection coll = db.getCollection("performance");
    BasicDBObject query = new BasicDBObject();

    query.put("_id", doc.get("name"));

    DBCursor cursor = coll.find(query);

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

    if (cursor.count() > 0) {
      LOG.info("Performance Results Found and Updated: " + coll.update(query, doc, true, false));
      json = Json.createReader(new StringReader(perfResults)).readObject();
      return arrBuild.add(json).build();
    } else {
      LOG.info("Performance Results Created: " + coll.insert(doc));
      json = Json.createReader(new StringReader(perfResults)).readObject();
      return arrBuild.add(json).build();
    }
  }
Пример #3
0
  @Override
  public void execute() throws BuildException {
    if (index == null) {
      throw new BuildException("Required attributes: file");
    }

    try {
      JsonObjectBuilder jsonRoot = Json.createObjectBuilder();

      JsonArrayBuilder jsonKeyrings = Json.createArrayBuilder();
      getKeyRings().forEach(jsonKeyrings::add);
      jsonRoot.add("keyrings", jsonKeyrings);

      JsonArrayBuilder jsonPackages = Json.createArrayBuilder();
      getPackages()
          .forEach(
              (p) -> {
                JsonObjectBuilder jsonPackage = Json.createObjectBuilder();
                p.forEach(
                    (k, v) -> {
                      if (v instanceof Boolean) {
                        jsonPackage.add(k, (Boolean) v); // Boolean
                      } else if (v instanceof Number) {
                        jsonPackage.add(k, ((Number) v).longValue()); // Integer
                      } else if (v instanceof String[]) {
                        JsonArrayBuilder array = Json.createArrayBuilder(); // String Array
                        for (String s : (String[]) v) {
                          array.add(s);
                        }
                        jsonPackage.add(k, array);
                      } else if (v == null) {
                        jsonPackage.addNull(k); // null
                      } else {
                        jsonPackage.add(k, v.toString()); // String
                      }
                    });
                jsonPackages.add(jsonPackage);
              });
      jsonRoot.add("packages", jsonPackages);

      log("Write Package Source: " + index);
      StringWriter json = new StringWriter();
      try (JsonWriter writer =
          Json.createWriterFactory(singletonMap(JsonGenerator.PRETTY_PRINTING, true))
              .createWriter(json)) {
        writer.writeObject(jsonRoot.build());
      }
      Files.write(index.toPath(), json.toString().trim().getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
      throw new BuildException(e);
    }
  }
 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();
 }
Пример #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();
 }
Пример #8
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";
    }
  }
Пример #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();
    }
  }
Пример #10
0
  public String toJSON() {
    JsonArrayBuilder nodearray = Json.createArrayBuilder();
    if (nodeTemplatelist == null) logger.error("nodeTemplatelist is empty");
    for (NodeTemplateCount process : nodeTemplatelist) {

      nodearray.add(process.getCount());
    }
    JsonObject model =
        Json.createObjectBuilder()
            .add("name", this.name)
            .add("plugin_name", this.pluginName)
            .add("hadoop_version", this.hadoopVersion)
            .add("node_processes", nodearray)
            .build();

    StringWriter stWriter = new StringWriter();
    try (JsonWriter jsonWriter = Json.createWriter(stWriter)) {
      jsonWriter.writeObject(model);
    }

    String jsonData = stWriter.toString();
    System.out.println(jsonData);

    return jsonData;
  }
  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();
  }
 @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();
   }
 }
Пример #13
0
  public static JsonArray arrayToJson(Collection<?> array) {

    JsonArrayBuilder json = Json.createArrayBuilder();

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

    return json.build();
  }
Пример #14
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();
  }
Пример #16
0
 private static Response createDataverse(TestDataverse dataverseToCreate, TestUser creator) {
   JsonArrayBuilder contactArrayBuilder = Json.createArrayBuilder();
   contactArrayBuilder.add(Json.createObjectBuilder().add("contactEmail", creator.getEmail()));
   JsonArrayBuilder subjectArrayBuilder = Json.createArrayBuilder();
   subjectArrayBuilder.add("Other");
   JsonObject dvData =
       Json.createObjectBuilder()
           .add("alias", dataverseToCreate.alias)
           .add("name", dataverseToCreate.name)
           .add("dataverseContacts", contactArrayBuilder)
           .add("dataverseSubjects", subjectArrayBuilder)
           .build();
   Response createDataverseResponse =
       given()
           .body(dvData.toString())
           .contentType(ContentType.JSON)
           .when()
           .post("/api/dataverses/:root?key=" + creator.apiToken);
   return createDataverseResponse;
 }
Пример #17
0
  // TODO: Remove this @RequiresPermissions, as it is added to test permission workflow
  // @RequiresPermissions(value = "lookup:semester")
  public JsonObject buildSemesters(final List<Semester> pSemesters, final UriInfo pUriInfo) {

    JsonObjectBuilder object = Json.createObjectBuilder();
    JsonArrayBuilder children = Json.createArrayBuilder();
    LocalCache localCache = new LocalCache();
    for (Semester readOnly : pSemesters) {
      children.add(toJson(readOnly, pUriInfo, localCache));
    }
    object.add("entries", children);
    localCache.invalidate();
    return object.build();
  }
 @Override
 public JsonArrayBuilder generate(SourceOfRandomness random, GenerationStatus status) {
   JsonArrayBuilder builder = Json.createArrayBuilder();
   while (true) {
     Integer pickType = random.nextInt(0, 5);
     Integer shouldEnd = random.nextInt(0, 10);
     if (shouldEnd == 10 || depth > 5) {
       return builder;
     }
     if (pickType == 0) {
       builder.add(new ReadableStringGenerator().generate(random, status));
     } else if (pickType == 1) {
       builder.add(new IntegerGenerator().generate(random, status));
     } else if (pickType == 2) {
       builder.add(random.nextBoolean());
     } else if (pickType == 3) {
       builder.add(new JsonObjectBuilderGenerator(depth + 1).generate(random, status));
     } else if (pickType == 4) {
       builder.add(new JsonArrayBuilderGenerator(depth + 1).generate(random, status));
     }
   }
 }
Пример #19
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();
  }
Пример #20
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;
 }
 // email, password
 // notificationType, notficationId,
 @POST
 @Path("getall")
 @Consumes("application/json")
 @Produces("application/json")
 public JsonObject putJson(JsonObject content) {
   String email = content.getString(JsonStrings.email);
   String password = content.getString(JsonStrings.password);
   JsonObjectBuilder builder = Json.createObjectBuilder();
   User user = null;
   try {
     user =
         em.createNamedQuery("User.findByEmail", User.class)
             .setParameter("email", email)
             .getSingleResult();
   } catch (NoResultException e) {
   }
   if (user == null) {
     throw new UnsupportedOperationException();
   }
   if (!user.getPassword().equals(password)) {
     throw new UnsupportedOperationException();
   }
   activeBean.register(content, user);
   em.refresh(em.merge(user));
   Collection<UsersNotifications> usersNotifications = null;
   usersNotifications = user.getUsersNotificationsCollection();
   if (usersNotifications == null || usersNotifications.isEmpty()) {
     builder.add(JsonStrings.newNotifications, false);
     return builder.build();
   }
   builder.add(JsonStrings.newNotifications, true);
   JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
   for (UsersNotifications notification : usersNotifications) {
     JsonObjectBuilder internalBuilder = Json.createObjectBuilder();
     internalBuilder.add(JsonStrings.notificationType, notification.getNotificationType());
     internalBuilder.add(JsonStrings.notificationItemId, notification.getNotifyId());
     arrayBuilder.add(internalBuilder);
   }
   em.createNamedQuery("UsersNotifications.deleteByUserId")
       .setParameter("userId", user)
       .executeUpdate();
   em.flush();
   builder.add(JsonStrings.notificationTable, arrayBuilder);
   return builder.build();
 }
  public static JsonArrayBuilder getWorkplaces() throws SQLException {
    JsonArrayBuilder array = Json.createArrayBuilder();
    String q = "SELECT IdPlace, PlaceName, PlaceAddress " + "FROM place ";

    PreparedStatement st = Conn.prepare(q);
    ResultSet u = st.executeQuery();

    while (u.next()) {
      JsonObjectBuilder builder = Json.createObjectBuilder();
      builder.add("id", u.getInt("IdPlace"));
      builder.add("name", u.getString("PlaceName"));
      builder.add("address", u.getString("PlaceAddress"));

      array.add(builder);
    }

    return array;
  }
  public void sendToFinance() {
    ConnectionGetter cg = new ConnectionGetter();
    con = cg.getConnection();
    try {
      st = con.createStatement();
      ResultSet rs =
          st.executeQuery(
              "Select i.*,j.outstanding_amount from PAYMENTS_SUMMARY i, payments_outstanding_summary j where BILL_CYCLE_DATE='20-aug-2015' and i.account_number=j.account_number ORDER BY i.account_number");
      JsonObjectBuilder accountInfo = Json.createObjectBuilder();
      JsonArrayBuilder paymentArray = Json.createArrayBuilder();
      JsonObjectBuilder paymentDB = Json.createObjectBuilder();

      while (rs.next()) {
        int accountNumber = rs.getInt("account_number");
        int billedAmount = rs.getInt("billed_amount");
        int amountReceived = rs.getInt("amount_recieved");
        // int outstandingAmount=rs.getInt("outstanding_amount");
        Date paymentDate = rs.getDate("payment_date");
        String paymentDateString;
        if (rs.wasNull()) paymentDateString = "Not Paid";
        else paymentDateString = new SimpleDateFormat("dd/MM/yyyy").format(paymentDate);
        Date billCycleDate = rs.getDate("bill_cycle_date");
        String billCycleDateString = new SimpleDateFormat("dd/MM/yyyy").format(billCycleDate);

        accountInfo.add("accountNumber", accountNumber);
        accountInfo.add("billedAmount", billedAmount);
        accountInfo.add("amountReceived", amountReceived);
        //		accountInfo.add("outstandingAmount", outstandingAmount);
        accountInfo.add("paymentDate", paymentDateString);
        accountInfo.add("billCycleDate", billCycleDateString);

        paymentArray.add(accountInfo);
      }
      paymentDB.add("payments", paymentArray);
      String jsonObj = new GsonBuilder().setPrettyPrinting().create().toJson(paymentDB.build());

      dataForFinance = jsonObj;
      //		System.out.println(dataForFinance);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #24
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;
  }
Пример #26
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;
 }
Пример #27
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();
 }
Пример #28
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();
 }
Пример #29
0
  /**
   * The response entity from message service is
   * {"statusCode":"000000","templateSMS":{"dateCreated":"20140827105250",
   * "smsMessageSid":"20140827105250065847"}}
   *
   * @param phoneNumber
   * @return
   * @throws NoSuchAlgorithmException
   * @throws UnsupportedEncodingException
   */
  @GET
  @Path("registration/sms")
  @Produces(MediaType.APPLICATION_JSON)
  public Response sendVerifyMessageToMobile(@QueryParam("phoneNumber") String phoneNumber)
      throws NoSuchAlgorithmException, UnsupportedEncodingException {
    if (phoneNumber == null) {
      return Response.ok(
              new PhoneVerifyResponse(
                  AuthenticationConstants.MESSAGESENDFAILURE,
                  "Parameter phoneNumber provided is null",
                  null))
          .build();
    }
    Properties tzProperties = PropertiesUtils.getProperties(servletConfig.getServletContext());
    SslConfigurator sslConfig =
        SslConfigurator.newInstance()
            .trustStoreFile(tzProperties.getProperty("ssl.trust.store.file"))
            .trustStorePassword(tzProperties.getProperty("ssl.trust.store.pass"))
            .trustStoreType("JKS")
            .trustManagerFactoryAlgorithm("PKIX")
            .keyStoreFile(tzProperties.getProperty("ssl.key.store.file"))
            .keyPassword(tzProperties.getProperty("ssl.key.store.pass"))
            .keyStoreType("JKS")
            .keyManagerFactoryAlgorithm("SunX509")
            .keyStoreProvider("SUN")
            .securityProtocol("SSL");

    SSLContext sslContext = sslConfig.createSSLContext();
    Client client = ClientBuilder.newBuilder().sslContext(sslContext).build();

    WebTarget target = client.target(tzProperties.getProperty("mobile.verify.service"));
    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    String accountSid = tzProperties.getProperty("mobile.account.sid");
    String encodeString = accountSid + tzProperties.getProperty("mobile.auth.token") + timeStamp;
    String authenticationString = accountSid + ":" + timeStamp;
    String sig = new EncryptUtil().md5Digest(encodeString);

    JsonObjectBuilder messageBuilder = Json.createObjectBuilder();
    JsonArrayBuilder datasBuilder = Json.createArrayBuilder();
    String verificationCode = String.valueOf(VerificationCodeGenerator.randInt(100000, 999999));
    datasBuilder.add(verificationCode).add(tzProperties.getProperty("mobile.code.active.time"));
    messageBuilder
        .add("to", phoneNumber)
        .add("appId", tzProperties.getProperty("mobile.appid"))
        .add("templateId", tzProperties.getProperty("mobile.templateid"))
        .add("datas", datasBuilder);

    Response providerResponse =
        target
            .queryParam("sig", sig)
            .request(MediaType.APPLICATION_JSON)
            .header(HttpHeaders.AUTHORIZATION, Base64.encodeAsString(authenticationString))
            .post(Entity.entity(messageBuilder.build(), MediaType.APPLICATION_JSON));
    JsonObject jsonObject = providerResponse.readEntity(JsonObject.class);
    if (jsonObject.getString("statusCode").equals("000000")) {
      TokenHolder.verificationCodeMap.put(phoneNumber, verificationCode);
      return Response.ok(
              new PhoneVerifyResponse(
                  AuthenticationConstants.MESSAGESENDSUCCESS,
                  jsonObject.toString(),
                  verificationCode))
          .build();
    } else {
      return Response.ok(
              new PhoneVerifyResponse(
                  AuthenticationConstants.MESSAGESENDFAILURE, jsonObject.toString(), null))
          .build();
    }
  }