Ejemplo n.º 1
0
  /**
   * Converts partition info into a JSON object.
   *
   * @param partitionInfo partition descriptions
   */
  private JsonNode json(List<PartitionInfo> partitionInfo) {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode partitions = mapper.createArrayNode();

    // Create a JSON node for each partition
    partitionInfo
        .stream()
        .forEach(
            info -> {
              ObjectNode partition = mapper.createObjectNode();

              // Add each member to the "members" array for this partition
              ArrayNode members = partition.putArray("members");
              info.members().stream().forEach(members::add);

              // Complete the partition attributes and add it to the array
              partition
                  .put("name", info.name())
                  .put("term", info.term())
                  .put("leader", info.leader());
              partitions.add(partition);
            });

    return partitions;
  }
 @Override
 public ObjectNode encodeJSON(Activities t, AccessRights rights, MediaType mt) {
   ObjectNode root = getJsonFactory().objectNode();
   ArrayNode activities = root.putArray(JSONConstants.ACTIVITIES_KEY);
   for (Activity a : t) {
     activities.add(activityEncoder.encodeJSON(a, rights, mt));
   }
   return root;
 }
Ejemplo n.º 3
0
 private ObjectNode encodeSweCountRangeField(SweField field) {
   ObjectNode jfield = createField(field);
   jfield.put(JSONConstants.TYPE, JSONConstants.COUNT_RANGE_TYPE);
   SweCountRange sweCountRange = (SweCountRange) field.getElement();
   if (sweCountRange.isSetValue()) {
     ArrayNode av = jfield.putArray(JSONConstants.VALUE);
     av.add(sweCountRange.getValue().getRangeStart());
     av.add(sweCountRange.getValue().getRangeEnd());
   }
   return jfield;
 }
 protected <T> ObjectNode toJsonBase(Attribute<T> src) {
   ObjectNode root = mapper.createObjectNode();
   root.put("visibility", src.getVisibility().name());
   if (src.getRemoteIdp() != null) root.put("remoteIdp", src.getRemoteIdp());
   if (src.getTranslationProfile() != null)
     root.put("translationProfile", src.getTranslationProfile());
   ArrayNode values = root.putArray("values");
   AttributeValueSyntax<T> syntax = src.getAttributeSyntax();
   for (T value : src.getValues()) values.add(syntax.serialize(value));
   return root;
 }
Ejemplo n.º 5
0
 private JsonNode getJsonPoints(JsonNode response) {
   ObjectNode result = Json.newObject();
   result.put("result", "ok");
   ArrayNode responseArray = (ArrayNode) response.get("hits").get("hits");
   ArrayNode pointsArray = Json.newArray();
   for (JsonNode item : responseArray) {
     pointsArray.add(item);
   }
   result.putArray("points").addAll(pointsArray);
   return result;
 }
 @Override
 public String getSerializedConfiguration() throws InternalException {
   ObjectNode main = Constants.MAPPER.createObjectNode();
   ArrayNode allow = main.putArray("allowed");
   for (String a : allowed) allow.add(a);
   try {
     return Constants.MAPPER.writeValueAsString(main);
   } catch (JsonProcessingException e) {
     throw new InternalException("Can't serialize EnumAttributeSyntax to JSON", e);
   }
 }
Ejemplo n.º 7
0
 private ObjectNode encodeSweTimeRangeField(SweField field) {
   ObjectNode jfield = createField(field);
   jfield.put(JSONConstants.TYPE, JSONConstants.TIME_RANGE_TYPE);
   SweTimeRange sweTimeRange = (SweTimeRange) field.getElement();
   jfield.put(JSONConstants.UOM, sweTimeRange.getUom());
   if (sweTimeRange.isSetValue()) {
     ArrayNode av = jfield.putArray(JSONConstants.VALUE);
     av.add(DateTimeHelper.formatDateTime2IsoString(sweTimeRange.getValue().getRangeStart()));
     av.add(DateTimeHelper.formatDateTime2IsoString(sweTimeRange.getValue().getRangeEnd()));
   }
   return jfield;
 }
Ejemplo n.º 8
0
 /**
  * Get details of all port pairs created.
  *
  * @return 200 OK
  */
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response getPortPairs() {
   Iterable<PortPair> portPairs = get(PortPairService.class).getPortPairs();
   ObjectNode result = mapper().createObjectNode();
   ArrayNode portPairEntry = result.putArray("port_pairs");
   if (portPairs != null) {
     for (final PortPair portPair : portPairs) {
       portPairEntry.add(codec(PortPair.class).encode(portPair, this));
     }
   }
   return ok(result.toString()).build();
 }
Ejemplo n.º 9
0
 /**
  * Retrieve details of all paths created.
  *
  * @return 200 OK
  */
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response queryAllPath() {
   log.debug("Query all paths.");
   Iterable<Tunnel> tunnels = get(PceService.class).queryAllPath();
   ObjectNode result = mapper().createObjectNode();
   ArrayNode pathEntry = result.putArray("paths");
   if (tunnels != null) {
     for (final Tunnel tunnel : tunnels) {
       PcePath path = DefaultPcePath.builder().of(tunnel).build();
       pathEntry.add(codec(PcePath.class).encode(path, this));
     }
   }
   return ok(result.toString()).build();
 }
Ejemplo n.º 10
0
  /**
   * REST endpoint returns a json array containing metadata about the currently logged in user's
   * uploaded files.
   *
   * @return json containing file upload ids and filenames
   */
  public Result listUploads() {
    List<UserUpload> uploadList = UserUpload.findUploadsByUserId(Application.getCurrentUserId());

    ObjectNode response = Json.newObject();
    ArrayNode uploads = response.putArray("uploads");

    for (UserUpload userUpload : uploadList) {
      ObjectNode upload = Json.newObject();
      upload.put("id", userUpload.id);
      upload.put("filename", userUpload.fileName);
      uploads.add(upload);
    }

    return ok(uploads);
  }
Ejemplo n.º 11
0
  @Override
  public ObjectNode encode(TrafficSelector selector, CodecContext context) {
    checkNotNull(selector, "Traffic selector cannot be null");

    final ObjectNode result = context.mapper().createObjectNode();
    final ArrayNode jsonCriteria = result.putArray(CRITERIA);

    if (selector.criteria() != null) {
      final JsonCodec<Criterion> criterionCodec = context.codec(Criterion.class);
      for (final Criterion criterion : selector.criteria()) {
        jsonCriteria.add(criterionCodec.encode(criterion, context));
      }
    }

    return result;
  }
  protected void handleEvent(JsonNode event) { // obslug eventow z websocketa

    if (!event.has("request")) {
      return;
    }

    String request = event.get("request").asText();

    if (request.equals("geolocation")) {
      handleGeolocation(event);
      return;
    } else if (request.equals("search")) {

      // get request data
      String pattern = event.get("pattern").asText();
      Boolean limit = event.get("limit").asText().equals("true");
      List<String> tagList = ctxEx.extractTags(pattern);
      String searchPattern = ctxEx.stripTags(pattern);

      Logger.info("searching for:" + pattern + " with" + (limit ? "out" : "") + " limit");
      Logger.info("search:" + searchPattern + "\ntags:" + tagList.toString());

      ArrayList<ArrayList<String>> searchResult = search(searchPattern, limit);

      if (!tagList.isEmpty()) searchResult = filterOutByTags(searchResult, tagList);

      if (searchResult == null) {
        sendEmptyResults();
      } else {
        Logger.info(String.valueOf(searchResult.size()) + " found");

        ObjectNode message = Json.newObject(); // create message

        ArrayNode results = message.putArray("result"); // results array in message
        Set<String> tagsSet = new HashSet<>();

        for (ArrayList<String> result : searchResult) {
          ObjectNode innerMsg = Json.newObject(); // inner message (file info)
          innerMsg.put("file", result.get(0));
          innerMsg.put("link", result.get(1));
          innerMsg.put("size", result.get(2));

          ArrayNode tags = innerMsg.putArray("tags"); // tags array in innerMsg (for this file)
          // odejmujemy 4 ze wzgledu na to ze na poczatku sa 4 elementy ktore nie sa tagami
          int tagcount = result.size() - 4;
          for (int tagnr = 0; tagnr < tagcount - 2; tagnr++) {
            tags.add(result.get(4 + tagnr));
            tagsSet.add("\"" + result.get(4 + tagnr) + "\"");
          }
          String tempCont = ctxEx.getContext(result.get(3), searchPattern);
          innerMsg.put("context", tempCont);
          innerMsg.put("lat", result.get(result.size() - 2));
          innerMsg.put("lng", result.get(result.size() - 1));
          results.add(innerMsg);
        }
        int temp = searchResult.size();
        String temp2 = "" + temp;
        message.put("resultsCount", temp2);
        message.put("tagList", tagsSet.toString());
        socketOut.write(message);
      }
    }
  }
  // This test is to verify RAW JSON structured query
  @Test
  public void testBulkSearchRawJSONStrucQD() throws Exception {
    //		setAutomaticDirectoryCreation(dbName,"automatic");
    setMaintainLastModified(dbName, true);
    this.loadJSONDocuments();
    this.loadXMLDocuments();
    GenericDocumentManager docMgr = client.newDocumentManager();
    QueryManager queryMgr = client.newQueryManager();
    JacksonHandle jh = new JacksonHandle();
    ObjectMapper mapper = new ObjectMapper();
    //	constructing JSON representation of Raw JSON Structured Query

    ObjectNode txtNode = mapper.createObjectNode();
    txtNode.putArray("text").add("woof");
    ObjectNode termQNode = mapper.createObjectNode();
    termQNode.set("term-query", txtNode);
    ObjectNode queriesArrayNode = mapper.createObjectNode();
    queriesArrayNode.putArray("queries").add(termQNode);

    ObjectNode txtNode2 = mapper.createObjectNode();
    txtNode2.putArray("text").add("bar");
    ObjectNode termQNode2 = mapper.createObjectNode();
    termQNode2.set("term-query", txtNode2);
    queriesArrayNode.withArray("queries").add(termQNode2);

    ObjectNode orQueryNode = mapper.createObjectNode();
    orQueryNode.set("or-query", queriesArrayNode);

    ObjectNode queryArrayNode = mapper.createObjectNode();
    queryArrayNode.putArray("queries").add(orQueryNode);
    ObjectNode mainNode = mapper.createObjectNode();
    mainNode.set("query", queryArrayNode);
    jh.set(mainNode);
    RawStructuredQueryDefinition qd = queryMgr.newRawStructuredQueryDefinition(jh);
    System.out.println(jh.get().toString());
    docMgr.setNonDocumentFormat(Format.JSON);
    JacksonHandle results = new JacksonHandle();
    DocumentPage page = docMgr.search(qd, 1, results);
    DocumentMetadataHandle mh = new DocumentMetadataHandle();

    int count = 1;
    while (count < 4) {
      page = docMgr.search(qd, count, results);

      while (page.hasNext()) {
        DocumentRecord rec = page.next();
        if (rec.getMimetype().contains("xml")) {
          validateRecord(rec, Format.XML);
        } else {
          validateRecord(rec, Format.JSON);
        }
        docMgr.readMetadata(rec.getUri(), mh);
        assertTrue("Records has permissions? ", mh.getPermissions().containsKey("flexrep-eval"));
        assertFalse("Record has collections ?", mh.getCollections().isEmpty());
      }

      count++;
    }
    System.out.println(results.get().toString());
    assertEquals(
        "Total search results before transaction rollback are ",
        "204",
        results.get().get("total").asText());
  }