net.minidev.json.JSONArray Java Examples

The following examples show how to use net.minidev.json.JSONArray. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MCDownloadOnlineVersionList.java    From mclauncher-api with MIT License 6 votes vote down vote up
@Override
public void startDownload() throws Exception {
    // at first, we download the complete version list
    String jsonString = HttpUtils.httpGet(JSONVERSION_LIST_URL);
    JSONObject versionInformation = (JSONObject) JSONValue.parse(jsonString);
    JSONArray versions = (JSONArray) versionInformation.get("versions");

    versionsToUrlMap = new HashMap<>();
    // and then, for each version...
    for (Object object : versions) {
        JSONObject versionObject = (JSONObject) object;
        String id = versionObject.get("id").toString();
        versionsToUrlMap.put(id, versionObject.get("url").toString());
        notifyObservers(id);
    }
}
 
Example #2
Source File: JwtGeneratorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenFromTemplateWithScopesAndAttributes() throws IOException {
	jwtGenerator.setUserName(MY_USER_NAME);
	Jwt jwt = jwtGenerator.createFromTemplate("/claims_template.txt");

	assertThat(jwt.getClaimAsString("client_id"), equalTo(MY_CLIENT_ID));
	assertThat(jwt.getClaimAsString("zid"), startsWith(MY_SUBDOMAIN));
	assertThat(jwt.getClaimAsString("user_name"), equalTo(MY_USER_NAME));
	assertThat(jwt.getClaimAsString("email"), startsWith(MY_USER_NAME));
	assertThat(getExternalAttributeFromClaim(jwt, "zdn"), equalTo(MY_SUBDOMAIN));

	assertThat(jwt.getClaimAsStringList("scope"), hasItems("openid", "testScope", "testApp.localScope"));

	Map<String, Object> attributes = jwt.getClaimAsMap("xs.user.attributes");
	assertThat((JSONArray) attributes.get("usrAttr"), contains("value_1", "value_2"));
	jwt.getTokenValue();
}
 
Example #3
Source File: XsuaaToken.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
private String[] getStringListAttributeFromClaim(String attributeName, String claimName) {
	String[] attributeValues = null;

	Map<String, Object> claimMap = getClaimAsMap(claimName);
	if (claimMap == null) {
		logger.debug("Claim '{}' not found. Returning null.", claimName);
		return attributeValues;
	}

	// convert JSONArray to String[]
	JSONArray attributeJsonArray = (JSONArray) claimMap.get(attributeName);
	if (attributeJsonArray != null) {
		attributeValues = new String[attributeJsonArray.size()];
		for (int i = 0; i < attributeJsonArray.size(); i++) {
			attributeValues[i] = (String) attributeJsonArray.get(i);
		}
	}

	if (attributeValues == null) {
		logger.debug("Attribute '{}' in claim '{}' not found. Returning null.", attributeName, claimName);
		return attributeValues;
	}

	return attributeValues;
}
 
Example #4
Source File: YDLoginResponse.java    From mclauncher-api with MIT License 6 votes vote down vote up
public YDLoginResponse(JSONObject json) {
    super(json);
    sessionID = json.get("accessToken").toString();
    clientToken = json.get("clientToken").toString();
    selectedProfile = new YDPartialGameProfile((JSONObject) json.get("selectedProfile"));
    JSONArray profiles = (JSONArray) json.get("availableProfiles");
    if (profiles != null) {
        for (Object object : profiles) {
            JSONObject jsonObj = (JSONObject) object;
            YDPartialGameProfile p = new YDPartialGameProfile(jsonObj);
            this.profiles.put(p.getName(), p);
        }
    }
    if (json.containsKey("user"))
        user = new YDUserObject((JSONObject) json.get("user"));
}
 
Example #5
Source File: JSON.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static String reportToJson(ResourceReport r) {
    JSONObject json = new JSONObject();

    json.put("start", r.getStart());
    json.put("end", r.getEnd());
    json.put("resource", r.getResource());
    if (r.hasResourceID())
        json.put("resourceID", r.getResourceID());
    json.put("machine", r.getMachine());
    json.put("processID", r.getProcessID());
    if (r.hasProcessName())
        json.put("processName", r.getProcessName());
    if (r.hasUtilization())
        json.put("utilization", r.getUtilization());

    JSONArray reports = new JSONArray();
    for (TenantOperationReport report : r.getTenantReportList()) {
        reports.add(tenantReportToJSON(report));
    }
    json.put("tenantReports", reports);

    return json.toString();
}
 
Example #6
Source File: PathsRetainerTest.java    From json-smart-v2 with Apache License 2.0 6 votes vote down vote up
private PathsRetainer switchKeyToRemove() {
	long m = System.currentTimeMillis();
	if (keyToKeep == null && m % 4 == 0) {
		System.out.println("cast to String");
		return new PathsRetainer((String) null);
	} else if (keyToKeep == null && m % 4 == 1) {
		System.out.println("cast to String[]");
		return new PathsRetainer((String[]) null);
	} else if (keyToKeep == null && m % 4 == 2) {
		System.out.println("cast to JSONArray");
		return new PathsRetainer((JSONArray) null);
	} else if (keyToKeep == null && m % 4 == 3) {
		System.out.println("cast to List<String>");
		return new PathsRetainer((List<String>) null);
	} else if (keyToKeep instanceof String) {
		return new PathsRetainer((String) keyToKeep);
	} else if (keyToKeep instanceof String[]) {
		return new PathsRetainer((String[]) keyToKeep);
	} else if (keyToKeep instanceof JSONArray) {
		return new PathsRetainer((JSONArray) keyToKeep);
	} else if (keyToKeep instanceof List<?>) {
		return new PathsRetainer((List<String>) keyToKeep);
	} else {
		throw new IllegalArgumentException("bad test setup: wrong type of key to remove");
	}
}
 
Example #7
Source File: XsuaaServicesParser.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
private static JSONObject getJSONObjectFromTag(final JSONArray jsonArray, String tag) {
	JSONObject xsuaaBinding = null;
	for (int i = 0; i < jsonArray.size(); i++) {
		JSONObject binding = (JSONObject) jsonArray.get(i);
		JSONArray tags = (JSONArray) binding.get(TAGS);

		Optional<String> planName = Optional.ofNullable(binding.getAsString("plan"));
		boolean isApiAccessPlan = (planName.isPresent() && planName.get().equals("apiaccess"));
		for (int j = 0; j < tags.size(); j++) {
			if (tags.get(j).equals(tag) && !isApiAccessPlan) {
				if (xsuaaBinding == null) {
					xsuaaBinding = binding;
				} else {
					throw new IllegalStateException(
							"Found more than one xsuaa bindings. Please consider unified broker plan.");
				}
			}
		}
	}
	return xsuaaBinding;
}
 
Example #8
Source File: JsonInputTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonInputPathResolution() throws KettleException {
  JsonInputField inputField = new JsonInputField( "value" );
  final String PATH = "$[*].name";
  inputField.setPath( PATH );
  inputField.setType( ValueMetaInterface.TYPE_STRING );
  JsonInputMeta inputMeta = createSimpleMeta( "json", inputField );
  VariableSpace variables = new Variables();
  JsonInput jsonInput = null;
  try {
    jsonInput =
      createJsonInput( "json", inputMeta, variables, new Object[] { getSampleJson() } );

    JsonInputData data = (JsonInputData) Whitebox.getInternalState( jsonInput, "data" );
    FastJsonReader reader = (FastJsonReader) Whitebox.getInternalState( data, "reader" );
    RowSet rowset = reader.parse( new ByteArrayInputStream( getSampleJson().getBytes() ) );
    List results = (List) Whitebox.getInternalState( rowset, "results" );
    JSONArray jsonResult = (JSONArray) results.get( 0 );

    assertEquals( 1, jsonResult.size() );
    assertEquals( "United States of America", jsonResult.get( 0 ) );

  } catch ( InvalidPathException pathException ) {
    assertNull( jsonInput );
  }
}
 
Example #9
Source File: JsonHelper.java    From hsac-fitnesse-fixtures with Apache License 2.0 6 votes vote down vote up
private JSONArray sort(final JsonPathHelper pathHelper, JSONArray a, final String nestedPathExpr) {
    List<String> elements = new ArrayList<>(a.size());
    for (Object element : a) {
        net.minidev.json.JSONObject jsonObject = new net.minidev.json.JSONObject((Map<String, ?>) element);
        elements.add(jsonObject.toJSONString());
    }
    Collections.sort(elements, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            Comparable val1 = (Comparable) pathHelper.getJsonPath(o1, nestedPathExpr);
            Comparable val2 = (Comparable) pathHelper.getJsonPath(o2, nestedPathExpr);
            return val1.compareTo(val2);
        }
    });
    return convertToArray(elements);
}
 
Example #10
Source File: SecretDetector.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
public static JSONArray maskJsonArray(JSONArray array)
{
  for (int i = 0; i < array.size(); i++)
  {
    Object node = array.get(i);
    if (node instanceof JSONObject)
    {
      maskJsonObject((JSONObject) node);
    }
    else if (node instanceof JSONArray)
    {
      maskJsonArray((JSONArray) node);
    }
    else if (node instanceof String)
    {
      array.set(i, SecretDetector.maskSecrets((String) node));
    }
    // for other types, we can just leave it untouched
  }

  return array;
}
 
Example #11
Source File: GrantedAuthoritiesConverter.java    From oauth2-resource with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
Collection<String> getRoles(String claimJsonString) {
    if (claimJsonString == null) {
        return Collections.emptyList();
    }

    Object document = Configuration.defaultConfiguration().jsonProvider().parse(claimJsonString);

    List<Object> authorities = JsonPath.using(conf).parse(document).read("$..roles");

    if (authorities == null || authorities.size() == 0) {
        authorities = JsonPath.using(conf).parse(document).read("$..authorities");
    }
    Collection<String> roles = new ArrayList<>();
    authorities.forEach(authorityItem -> {
        if (authorityItem instanceof String) {
            roles.add((String) authorityItem);
        } else if (authorityItem instanceof JSONArray) {
            roles.addAll((Collection<String>) authorityItem);
        } else if (authorityItem instanceof Collection) {
            roles.addAll((Collection<String>) authorityItem);
        }
    });

    return roles;
}
 
Example #12
Source File: SecretDetector.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
public static JSONObject maskJsonObject(JSONObject json)
{
  for (Map.Entry<String, Object> entry : json.entrySet())
  {
    if (entry.getValue() instanceof String)
    {
      entry.setValue(maskSecrets((String) entry.getValue()));
    }
    else if (entry.getValue() instanceof JSONArray)
    {
      maskJsonArray((JSONArray) entry.getValue());
    }
    else if (entry.getValue() instanceof JSONObject)
    {
      maskJsonObject((JSONObject) entry.getValue());
    }
  }
  return json;
}
 
Example #13
Source File: RestControllerV2IT.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
@Order(7)
void batchUpdateOnlyOneAttribute() {
  JSONObject jsonObject = new JSONObject();
  JSONArray entities = new JSONArray();

  JSONObject entity = new JSONObject();
  entity.put("id", 55);
  entity.put("xdatetime", "2015-01-05T08:30:00+0200");
  entities.add(entity);

  JSONObject entity2 = new JSONObject();
  entity2.put("id", 57);
  entity2.put("xdatetime", "2015-01-07T08:30:00+0200");
  entities.add(entity2);

  jsonObject.put("entities", entities);

  given(testUserToken)
      .contentType(APPLICATION_JSON)
      .body(jsonObject.toJSONString())
      .when()
      .put(API_V2 + "it_emx_datatypes_TypeTestv2/xdatetime")
      .then()
      .statusCode(OKE);
}
 
Example #14
Source File: ServiceControllerTest.java    From eureka-consul-adapter with MIT License 6 votes vote down vote up
@Test(timeout = 10000)
public void services_asyncChangesToMs1_interruptOnChange() throws Exception {

    Applications applications = mock2Applications();
    Mockito.when(registry.getApplications()).thenReturn(applications);

    startThread(() -> {
        sleepFor(1000);
        serviceChangeDetector.publish("ms1", 2);
        sleepFor(1000);
        serviceChangeDetector.publish("ms1", 3);
    });

    performAsync("/v1/catalog/services?wait=30s")
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(header().string("X-Consul-Index", "1"))
            .andExpect(jsonPath("$.ms1", Matchers.is(new JSONArray())))
            .andExpect(jsonPath("$.ms2", Matchers.is(new JSONArray())));

    performAsync("/v1/catalog/services?wait=30s&index=1")
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(header().string("X-Consul-Index", "2"))
            .andExpect(jsonPath("$.ms1", Matchers.is(new JSONArray())))
            .andExpect(jsonPath("$.ms2", Matchers.is(new JSONArray())));

}
 
Example #15
Source File: StaticRoutingConverter.java    From scheduler with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Convert a Routing implementation into a JSON object
 *
 * @param routing the routing implementation to convert
 * @return the JSON formatted routing object
 */
@Override
public JSONObject toJSON(StaticRouting routing) {
    JSONObject o = new JSONObject();
    o.put("type", getJSONId());
    JSONArray a = new JSONArray();
    Map<StaticRouting.NodesMap, Map<Link, Boolean>> routes = routing.getStaticRoutes();
    for (Map.Entry<StaticRouting.NodesMap, Map<Link, Boolean>> e : routes.entrySet()) {
        StaticRouting.NodesMap nm = e.getKey();
        JSONObject ao = new JSONObject();
        ao.put("nodes_map", nodesMapToJSON(nm));
        JSONArray links = new JSONArray();
        Map<Link, Boolean> v = e.getValue();
        for (Link l : v.keySet()) {
            JSONObject lo = new JSONObject();
            lo.put("link", l.id());
            lo.put("direction", routes.get(nm).get(l).toString());
            links.add(lo);
        }
        ao.put("links", links);
        a.add(ao);
    }
    o.put(ROUTES_LABEL, a);
    return o;
}
 
Example #16
Source File: JSON.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
/**
 * This method evaluates the jsonpath expression on the supplied
 * node.
 *
 * @param jsonpath The jsonpath expression
 * @param data The json data
 * @return The result, or null if not found (which may be due to an expression error)
 */
public static String evaluate(String jsonpath, Object data) {
    String json = serialize(data);

    // No jsonpath means return serialized form
    if (jsonpath == null || jsonpath.trim().isEmpty()) {
        return json;
    }

    if (json != null) {
        Object result = JsonPath.parse(json).read(jsonpath);
        if (result != null) {
            if (result.getClass() == JSONArray.class) {
                JSONArray arr=(JSONArray)result;
                if (arr.isEmpty()) {
                    result = null;
                } else if (arr.size() == 1) {
                    result = arr.get(0);
                }
            }
            return serialize(result);
        }
    }
    return null;
}
 
Example #17
Source File: MarcIteratorTest.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMarcSchemaIteration() {
  List<String> skippable = Arrays.asList("leader", "001", "003", "005", "006", "007", "008");
  // fixedValues
  for (JsonBranch branch : schema.getPaths()) {
    if (skippable.contains(branch.getLabel()) || branch.getParent() != null)
      continue;

    // List<Map<String, List<String>>> expectedList = fixedValues.get(branch.getLabel());
    JSONArray fieldInstances = (JSONArray) cache.getFragment(branch.getJsonPath());
    for (int fieldInsanceNr = 0; fieldInsanceNr < fieldInstances.size(); fieldInsanceNr++) {
      Map fieldInstance = (Map)fieldInstances.get(fieldInsanceNr);
      DataField field = MapToDatafield.parse(fieldInstance, MarcVersion.DNB);
      if (!fieldInstance.get("tag").equals("935")) {
        assertNotNull(fieldInstance.get("tag").toString() + " should not be null", field);
        assertEquals(fieldInstance.get("tag"), field.getTag());
      }
    }
  }
}
 
Example #18
Source File: ModelConverter.java    From scheduler with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Build VMs from a key.
 *
 * @param mo  the model to build
 * @param o   the object that contains the vm
 * @param key the key associated to the VMs
 * @return the resulting set of VMs
 * @throws JSONConverterException if at least one of the parsed VM already exists
 */
private static Set<VM> newVMs(Model mo, JSONObject o, String key) throws JSONConverterException {
    checkKeys(o, key);
    Object x = o.get(key);
    if (!(x instanceof JSONArray)) {
        throw new JSONConverterException("array expected at key '" + key + "'");
    }

    Set<VM> s = new HashSet<>(((JSONArray) x).size());
    for (Object i : (JSONArray) x) {
        int id = (Integer) i;
        VM vm = mo.newVM(id);
        if (vm == null) {
            throw JSONConverterException.vmAlreadyDeclared(id);
        }
        s.add(vm);
    }
    return s;
}
 
Example #19
Source File: WebServer.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/json");
    response.setStatus(HttpServletResponse.SC_OK);
    String uri = request.getRequestURI();
    int pathLen = request.getServletPath().length() + 1;
    String tagsString = uri.length() > pathLen ? uri.substring(pathLen) : "";
    String[] tags = tagsString.split(",");

    JSONObject obj = new JSONObject();
    for (String tag : tags) {
        JSONArray arr = new JSONArray();
        Collection<TaskRecord> taskInfos = metadata.getTasksByTag(tag, 0, Integer.MAX_VALUE);
        for (TaskRecord t : taskInfos) {
            arr.add(t.getTaskId().toString());
        }
        obj.put(tag, arr);
    }

    Writer out = response.getWriter();
    out.write(obj.toJSONString());
}
 
Example #20
Source File: TelemetryService.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Convert an event to a payload in string
 */
public String exportQueueToString(TelemetryEvent event)
{
  JSONArray logs = new JSONArray();
  logs.add(event);
  return logs.toString();
}
 
Example #21
Source File: TelemetryEvent.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * @return the deployment of this event
 */
public String getDeployment()
{
  JSONArray tags = (JSONArray) this.get("Tags");
  for (Object tag : tags)
  {
    JSONObject json = (JSONObject) tag;
    if (json.get("Name").toString().compareTo("deployment") == 0)
    {
      return json.get("Value").toString();
    }
  }
  return "Unknown";
}
 
Example #22
Source File: ArgumentList.java    From mclauncher-api with MIT License 5 votes vote down vote up
static ArgumentList fromArray(JSONArray array) {
    List<Argument> arguments = new ArrayList<>();
    for (Object a : array) {
        if (a instanceof String)
            arguments.add(Argument.fromString((String) a));
        else if(a instanceof JSONObject)
            arguments.add(Argument.fromJson((JSONObject) a));
    }
    return new ArgumentList(arguments);
}
 
Example #23
Source File: PathLocator.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public PathLocator(JSONArray pathsToFind) {
	if (pathsToFind == null || pathsToFind.isEmpty()) {
		this.pathsToFind = Collections.emptyList();
	} else {
		this.pathsToFind = new ArrayList<String>();
		for (Object s : pathsToFind) {
			this.pathsToFind.add((String) s);
		}
	}
}
 
Example #24
Source File: JSONs.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Read partitions of VMs.
 *
 * @param mo the associated model to browse
 * @param o  the object to parse
 * @param id the key in the map that points to the partitions
 * @return the parsed partition
 * @throws JSONConverterException if the key does not point to partitions of VMs
 */
public static Set<Collection<VM>> requiredVMPart(Model mo, JSONObject o, String id) throws JSONConverterException {
    Set<Collection<VM>> vms = new HashSet<>();
    Object x = o.get(id);
    if (!(x instanceof JSONArray)) {
        throw new JSONConverterException("Set of identifiers sets expected at key '" + id + "'");
    }
    for (Object obj : (JSONArray) x) {
        vms.add(vmsFromJSON(mo, (JSONArray) obj));
    }
    return vms;
}
 
Example #25
Source File: KinesisCompactionAcceptanceTest.java    From synapse with Apache License 2.0 5 votes vote down vote up
private void assertMessageForKey(LinkedHashMap<String, JSONArray> json, final Key expectedKey, String expectedPayload) {
    final Decoder<SnapshotMessage> decoder = new SnapshotMessageDecoder();
    JSONArray jsonArray = JsonPath.read(json, "$.data[?(@." + expectedKey.compactionKey() + ")]." + expectedKey.compactionKey());
    String messageJson = jsonArray.get(0).toString();
    TextMessage decoded = decoder.apply(new SnapshotMessage(Key.of(), Header.of(), messageJson));
    assertThat(decoded.getKey(), is(expectedKey));
    assertThat(decoded.getPayload(), is(expectedPayload));
}
 
Example #26
Source File: SplitConverter.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public JSONObject toJSON(Split o) {
    JSONObject c = new JSONObject();
    c.put("id", getJSONId());

    JSONArray a = new JSONArray();
    for (Collection<VM> grp : o.getSets()) {
        a.add(vmsToJSON(grp));
    }

    c.put("parts", a);
    c.put("continuous", o.isContinuous());
    return c;
}
 
Example #27
Source File: KinesisCompactionAcceptanceTest.java    From synapse with Apache License 2.0 5 votes vote down vote up
private void assertSnapshotFileStructureAndSize(LinkedHashMap<String, JSONArray> json,
                                                int expectedMinimumNumberOfRecords) {
    assertThat(json, hasJsonPath("$.startSequenceNumbers[0].shard", not(empty())));
    assertThat(json, hasJsonPath("$.startSequenceNumbers[0].sequenceNumber", not(empty())));

    assertThat(json, hasJsonPath("$.data", hasSize(greaterThanOrEqualTo(expectedMinimumNumberOfRecords))));
}
 
Example #28
Source File: KinesisCompactionAcceptanceTest.java    From synapse with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private LinkedHashMap<String, JSONArray> fetchAndParseSnapshotFileFromS3(String snapshotFileName) {
    GetObjectRequest request = GetObjectRequest.builder().bucket(INTEGRATION_TEST_BUCKET).key(snapshotFileName).build();

    ResponseInputStream<GetObjectResponse> responseInputStream = s3Client.getObject(request);
    try (
            BufferedInputStream bufferedInputStream = new BufferedInputStream(responseInputStream);
            ZipInputStream zipInputStream = new ZipInputStream(bufferedInputStream)
    ) {
        zipInputStream.getNextEntry();
        return (LinkedHashMap<String, JSONArray>) Configuration.defaultConfiguration().jsonProvider().parse(zipInputStream, Charsets.UTF_8.name());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #29
Source File: MongoResultsWriter.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
private void doWrite(Collection<RunResult> results) throws ParseException {

		Date now = new Date();
		StandardEnvironment env = new StandardEnvironment();

		String projectVersion = env.getProperty("project.version", "unknown");
		String gitBranch = env.getProperty("git.branch", "unknown");
		String gitDirty = env.getProperty("git.dirty", "no");
		String gitCommitId = env.getProperty("git.commit.id", "unknown");

		ConnectionString uri = new ConnectionString(this.uri);
		MongoClient client = MongoClients.create();

		String dbName = StringUtils.hasText(uri.getDatabase()) ? uri.getDatabase() : "spring-data-mongodb-benchmarks";
		MongoDatabase db = client.getDatabase(dbName);

		String resultsJson = ResultsWriter.jsonifyResults(results).trim();
		JSONArray array = (JSONArray) new JSONParser(JSONParser.MODE_PERMISSIVE).parse(resultsJson);
		for (Object object : array) {
			JSONObject dbo = (JSONObject) object;

			String collectionName = extractClass(dbo.get("benchmark").toString());

			Document sink = new Document();
			sink.append("_version", projectVersion);
			sink.append("_branch", gitBranch);
			sink.append("_commit", gitCommitId);
			sink.append("_dirty", gitDirty);
			sink.append("_method", extractBenchmarkName(dbo.get("benchmark").toString()));
			sink.append("_date", now);
			sink.append("_snapshot", projectVersion.toLowerCase().contains("snapshot"));

			sink.putAll(dbo);

			db.getCollection(collectionName).insertOne(fixDocumentKeys(sink));
		}

		client.close();
	}
 
Example #30
Source File: JSONs.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Read partitions of nodes.
 *
 * @param mo the associated model to browse
 * @param o  the object to parse
 * @param id the key in the map that points to the partitions
 * @return the parsed partition
 * @throws JSONConverterException if the key does not point to partitions of nodes
 */
public static Set<Collection<Node>> requiredNodePart(Model mo, JSONObject o, String id) throws JSONConverterException {
    Set<Collection<Node>> nodes = new HashSet<>();
    Object x = o.get(id);
    if (!(x instanceof JSONArray)) {
        throw new JSONConverterException("Set of identifiers sets expected at key '" + id + "'");
    }
    for (Object obj : (JSONArray) x) {
        nodes.add(nodesFromJSON(mo, (JSONArray) obj));
    }
    return nodes;
}