Exemplo n.º 1
0
  public static JsonValue removePaths(JsonValue jsonValue, Paths paths, Paths pathsToIgnore) {
    if (paths.matches(pathsToIgnore)) return JsonValue.NULL;

    if (jsonValue.isObject()) {
      paths = new Paths(paths);
      paths.extend("{}");

      if (paths.matches(pathsToIgnore)) return JsonValue.NULL;

      JsonObject jsonObject = new JsonObject();
      for (String name : jsonValue.asObject().names()) {
        Paths currentPaths = new Paths(paths);
        currentPaths.extend(name);
        jsonObject.set(
            name, removePaths(jsonValue.asObject().get(name), currentPaths, pathsToIgnore));
      }
      return jsonObject;
    }
    if (jsonValue.isArray()) {
      Paths currentPaths = new Paths(paths);
      currentPaths.extend("[]");

      if (currentPaths.matches(pathsToIgnore)) return JsonValue.NULL;

      JsonArray jsonArray = new JsonArray();
      for (int index = 0; index < jsonValue.asArray().size(); index++) {
        currentPaths = new Paths(paths);
        currentPaths.extend("[]", "[" + index + "]");

        jsonArray.add(removePaths(jsonValue.asArray().get(index), currentPaths, pathsToIgnore));
      }
      return jsonArray;
    }
    return jsonValue;
  }
Exemplo n.º 2
0
 public static JsonArray toJson(String[] arr) {
   JsonArray json = new JsonArray();
   for (int i = 0; i < arr.length; i++) {
     json.add(arr[i]);
   }
   return json;
 }
Exemplo n.º 3
0
 @Override
 public GroupChat createGroupChat(Contact... contacts) throws ConnectionException {
   JsonObject obj = new JsonObject();
   JsonArray allContacts = new JsonArray();
   allContacts.add(new JsonObject().add("id", "8:" + this.getUsername()).add("role", "Admin"));
   for (Contact contact : contacts) {
     allContacts.add(new JsonObject().add("id", "8:" + contact.getUsername()).add("role", "User"));
   }
   obj.add("members", allContacts);
   HttpURLConnection con =
       Endpoints.THREAD_URL
           .open(this)
           .as(HttpURLConnection.class)
           .expect(201, "While creating group chat")
           .post(obj);
   String url = con.getHeaderField("Location");
   Matcher chatMatcher = URL_PATTERN.matcher(url);
   if (chatMatcher.find()) {
     String id = chatMatcher.group(1);
     while (this.getChat(id) == null) ;
     return (GroupChat) this.getChat(id);
   } else {
     throw ExceptionHandler.generateException("No chat location", con);
   }
 }
 @Override
 public JsonObject toJson() {
   JsonObject root = new JsonObject();
   root.add("name", config.getName());
   JsonArray publisherList = new JsonArray();
   for (WanPublisherConfig publisherConfig : config.getWanPublisherConfigs()) {
     WanPublisherConfigDTO dto = new WanPublisherConfigDTO(publisherConfig);
     publisherList.add(dto.toJson());
   }
   root.add("publishers", publisherList);
   return root;
 }
 @Override
 public void fromJson(JsonObject json) {
   config = new WanReplicationConfig();
   config.setName(json.get("name").asString());
   List<WanPublisherConfig> publisherConfigs = config.getWanPublisherConfigs();
   JsonArray publishers = json.get("publishers").asArray();
   int size = publishers.size();
   for (int i = 0; i < size; i++) {
     WanPublisherConfigDTO dto = new WanPublisherConfigDTO(new WanPublisherConfig());
     dto.fromJson(publishers.get(0).asObject());
     publisherConfigs.add(dto.getConfig());
   }
 }
Exemplo n.º 6
0
  /** Tests GetAllMetrics method. */
  @Test
  public void testGetAllMetrics() {
    Counter onosCounter = new Counter();
    onosCounter.inc();

    Meter onosMeter = new Meter();
    onosMeter.mark();

    Timer onosTimer = new Timer();
    onosTimer.update(1, TimeUnit.MILLISECONDS);

    ImmutableMap<String, Metric> metrics =
        new ImmutableMap.Builder<String, Metric>()
            .put("onosCounter", onosCounter)
            .put("onosMeter", onosMeter)
            .put("onosTimer", onosTimer)
            .build();

    expect(mockMetricsService.getMetrics()).andReturn(metrics).anyTimes();

    replay(mockMetricsService);

    WebTarget wt = target();
    String response = wt.path("metrics").request().get(String.class);
    assertThat(response, containsString("{\"metrics\":["));

    JsonObject result = Json.parse(response).asObject();
    assertThat(result, notNullValue());

    JsonArray jsonMetrics = result.get("metrics").asArray();
    assertThat(jsonMetrics, notNullValue());
    assertThat(jsonMetrics.size(), is(3));

    assertTrue(
        matchesMetric(metrics.get("onosCounter")).matchesSafely(jsonMetrics.get(0).asObject()));
    assertTrue(
        matchesMetric(metrics.get("onosMeter")).matchesSafely(jsonMetrics.get(1).asObject()));
    assertTrue(
        matchesMetric(metrics.get("onosTimer")).matchesSafely(jsonMetrics.get(2).asObject()));
  }
Exemplo n.º 7
0
 @Override
 public void fillSyncedFileNames(JsonArray fileNames, ITernScriptPath path) {
   readLock.lock();
   try {
     Set<String> files;
     if (path != null) {
       files = syncedFilesPerPath.get(path);
     } else {
       files = sentFiles.keySet();
     }
     if (files != null) {
       for (String file : files) {
         fileNames.add(file);
       }
     }
   } finally {
     readLock.unlock();
   }
 }
Exemplo n.º 8
0
  private void _testGetAggregation(String uri) throws Exception {
    Response resp;

    URI aggrUri =
        buildURI(
            "/"
                + dbTmpName
                + "/"
                + collectionTmpName
                + "/"
                + RequestContext._AGGREGATIONS
                + "/"
                + uri);

    resp = adminExecutor.execute(Request.Get(aggrUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);
    HttpEntity entity = httpResp.getEntity();
    assertNotNull(entity);
    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode());
    assertNotNull("content type not null", entity.getContentType());
    assertEquals(
        "check content type",
        Representation.HAL_JSON_MEDIA_TYPE,
        entity.getContentType().getValue());

    String content = EntityUtils.toString(entity);

    assertNotNull("", content);

    JsonObject json = null;

    try {
      json = JsonObject.readFrom(content);
    } catch (Throwable t) {
      fail("parsing received json");
    }

    assertNotNull("check not null json response", json);
    assertNotNull("check not null _embedded", json.get("_embedded"));
    assertTrue("check _embedded", json.get("_embedded").isObject());

    assertNotNull("", json.get("_embedded").asObject().get("rh:result"));

    assertTrue(
        "check _embedded[\"rh:result\"]",
        json.get("_embedded").asObject().get("rh:result").isArray());

    JsonArray results = json.get("_embedded").asObject().get("rh:result").asArray();

    assertTrue("check we have 2 results", results.size() == 2);

    results
        .values()
        .stream()
        .map(
            (v) -> {
              assertNotNull("check not null _id property", v.asObject().get("_id"));
              return v;
            })
        .map(
            (v) -> {
              assertTrue(
                  "check results _id property is string", v.asObject().get("_id").isString());
              return v;
            })
        .map(
            (v) -> {
              assertNotNull("check not null value property", v.asObject().get("value"));
              return v;
            })
        .forEach(
            (v) -> {
              assertTrue(
                  "check results value property is number", v.asObject().get("value").isNumber());
            });
  }
Exemplo n.º 9
0
  @Test
  public void testGetMapReduceWithVariable() throws Exception {
    String uri = "avg_ages";

    String aggregationsMetadata =
        "{\"aggrs\": ["
            + "{"
            + "\"type\":\"mapReduce\""
            + ","
            + "\"uri\": \""
            + uri
            + "\","
            + "\"map\": \"function() { var minage = JSON.parse($vars).minage; if (this.age > minage ) { emit(this.name, this.age); }; }\","
            + "\"reduce\":\"function(key, values) { return Array.avg(values); }\""
            + ","
            + "\"query\":{\"name\":{\"_$var\":\"name\"}}"
            + "}]}";

    createTmpCollection();
    createMetadataAndTestData(aggregationsMetadata);

    Response resp;

    URI aggrUri =
        buildURI(
            "/"
                + dbTmpName
                + "/"
                + collectionTmpName
                + "/"
                + RequestContext._AGGREGATIONS
                + "/"
                + uri,
            new NameValuePair[] {
              new BasicNameValuePair("avars", "{\"name\": \"a\", \"minage\": 20}")
            });

    resp = adminExecutor.execute(Request.Get(aggrUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);
    HttpEntity entity = httpResp.getEntity();
    assertNotNull(entity);
    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode());
    assertNotNull("content type not null", entity.getContentType());
    assertEquals(
        "check content type",
        Representation.HAL_JSON_MEDIA_TYPE,
        entity.getContentType().getValue());

    String content = EntityUtils.toString(entity);

    assertNotNull("", content);

    JsonObject json = null;

    try {
      json = JsonObject.readFrom(content);
    } catch (Throwable t) {
      fail("parsing received json");
    }

    assertNotNull("check not null json response", json);
    assertNotNull("check not null _embedded", json.get("_embedded"));
    assertTrue("check _embedded", json.get("_embedded").isObject());

    assertNotNull("", json.get("_embedded").asObject().get("rh:result"));
    assertTrue(
        "check _embedded[\"rh:results\"]",
        json.get("_embedded").asObject().get("rh:result").isArray());

    JsonArray results = json.get("_embedded").asObject().get("rh:result").asArray();

    assertTrue("check we have 2 results", results.size() == 1);

    results
        .values()
        .stream()
        .map(
            (v) -> {
              assertNotNull("check not null _id property", v.asObject().get("_id"));
              return v;
            })
        .map(
            (v) -> {
              assertTrue(
                  "check results _id property is string", v.asObject().get("_id").isString());
              return v;
            })
        .map(
            (v) -> {
              assertTrue(
                  "check results _id property is a",
                  v.asObject().get("_id").asString().equals("a"));
              return v;
            })
        .map(
            (v) -> {
              assertNotNull("check not null value property", v.asObject().get("value"));
              return v;
            })
        .forEach(
            (v) -> {
              assertTrue(
                  "check results value property is number", v.asObject().get("value").isNumber());
            });
  }
Exemplo n.º 10
0
  public static Set<Mod> load(
      final Path path,
      final int order,
      final SettingsModelFactory settingsFactory,
      final DatabaseModelFactory databaseFactory,
      final LocalizerModelFactory localizerFactory) {

    log.debug("Loading mod: {}", path);

    Set<Mod> mods = new HashSet<>();

    // TODO Count all mods and send back progress info

    Set<Archive> archives = null;

    try {
      archives = processModFile(path, settingsFactory);
    } catch (IOException | StarDBException | ParseException e) {
      // TODO Error Dialogue
      log.error("", e);
      return new HashSet<Mod>();
    }

    for (Archive archive : archives) {

      Mod mod = new Mod(localizerFactory, settingsFactory);

      mod.setOrder(order);
      mod.files = new HashSet<>();
      mod.setArchiveName(archive.getFileName());

      // Get the modinfo file and parse it
      JsonObject obj = JsonObject.readFrom(new String(archive.getFile(".modinfo").getData()));

      mod.setInternalName(obj.get("name").asString());

      if (obj.get("version") != null) {
        mod.setGameVersion(obj.get("version").asString());
      } else {
        mod.setGameVersion("Field Empty");
      }

      Set<String> dependencies = new HashSet<>();
      Set<String> ignoredFileNames = new HashSet<>();

      if (obj.get("dependencies") != null) {
        JsonArray arr = obj.get("dependencies").asArray();
        for (int i = 0; i < arr.size(); i++) {
          dependencies.add(arr.get(i).asString());
        }
      }

      mod.setDependencies(dependencies);

      if (obj.get("metadata") != null) {

        JsonObject metadata = obj.get("metadata").asObject();

        mod.setDisplayName(JSONHelper.getString(metadata, "displayname", mod.getInternalName()));
        mod.setAuthor(JSONHelper.getString(metadata, "author", NO_AUTHOR));
        mod.setDescription(JSONHelper.getString(metadata, "description", NO_DESCRIPTION));
        mod.setURL(JSONHelper.getString(metadata, "support_url", ""));
        mod.setModVersion(JSONHelper.getString(metadata, "version", NO_VERSION));

        if (obj.get("ignoredfiles") != null) {
          JsonArray arr = obj.get("ignoredfiles").asArray();
          for (int i = 0; i < arr.size(); i++) {
            ignoredFileNames.add(arr.get(i).asString());
          }
        }

      } else {

        mod.setDisplayName(mod.getInternalName());
        mod.setAuthor(NO_AUTHOR);
        mod.setDescription(NO_DESCRIPTION);
        mod.setURL("");
        mod.setModVersion(NO_VERSION);
      }

      try {
        mod.setChecksum(
            FileHelper.getChecksum(
                new File(
                        settingsFactory.getInstance().getPropertyString("modsdir")
                            + File.separator
                            + mod.archiveName)
                    .toPath())); // TODO Better Path manipulation
      } catch (IOException e) {
        log.error("Setting Checksum", e);
      }

      for (ArchiveFile archiveFile : archive.getFiles()) {

        ModFile modFile = new ModFile();
        modFile.setPath(archiveFile.getPath());

        // Find and list all ignored files
        for (String ignored : ignoredFileNames) {
          if (archiveFile.getPath().endsWith(ignored) || archiveFile.getPath().endsWith(".txt")) {
            modFile.setIgnored(true);
          }
        }

        // Scan all json files and find those with mergeability
        if (!archiveFile.isFolder() && FileHelper.isJSON(archiveFile.getPath())) {

          modFile.setJson(true);

          String fileContents = new String(archiveFile.getData());

          if (fileContents.contains("__merge")) {
            modFile.setAutoMerged(true);
          }
        }

        if (!archiveFile.isFolder()) {
          mod.files.add(modFile);
        }
      }

      try {
        databaseFactory.getInstance().updateMod(mod);
      } catch (SQLException e) {
        log.error("", e);
        MessageDialogue dialogue =
            new MessageDialogue(
                localizer.getMessage("mod.dbconnectionerror"),
                localizer.getMessage("mod.dbconnectionerror.title"),
                MessageType.ERROR,
                new LocalizerFactory());
        dialogue.getResult();
        return new HashSet<Mod>();
      }

      mods.add(mod);
    }

    return mods;
  }