net.minidev.json.JSONObject Java Examples

The following examples show how to use net.minidev.json.JSONObject. 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: CertificateSetAndRegenerateTest.java    From credhub with Apache License 2.0 7 votes vote down vote up
@Test
public void certificateSetRequest_whenProvidedACertificateValueThatIsTooLong_returnsAValidationError()
        throws Exception {
    final int repetitionCount = 7001 - TEST_CERTIFICATE.length();
    final String setJson = JSONObject.toJSONString(
            ImmutableMap.<String, String>builder()
                    .put("ca_name", "")
                    .put("certificate", TEST_CERTIFICATE + StringUtils.repeat("a", repetitionCount))
                    .put("private_key", TEST_PRIVATE_KEY)
                    .build());

    final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data")
            .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
            .accept(APPLICATION_JSON)
            .contentType(APPLICATION_JSON)
            //language=JSON
            .content("{\n"
                    + "  \"name\" : \"/crusher\",\n"
                    + "  \"type\" : \"certificate\",\n"
                    + "  \"value\" : " + setJson + "}");

    this.mockMvc.perform(certificateSetRequest)
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.error", equalTo(
                    "The provided certificate value is too long. Certificate lengths must be less than 7000 characters.")));
}
 
Example #2
Source File: PicaReaderTest.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
private Map<String, List<PicaTagDefinition>> readSchema(JSONParser parser, String fileName) throws IOException, URISyntaxException, ParseException {
  Map<String, List<PicaTagDefinition>> map = new HashMap<>();

  Path tagsFile = FileUtils.getPath(fileName);
  Object obj = parser.parse(new FileReader(tagsFile.toString()));
  JSONObject jsonObject = (JSONObject) obj;
  JSONObject fields = (JSONObject) jsonObject.get("fields");
  for (String name : fields.keySet()) {
    JSONObject field = (JSONObject) fields.get(name);
    // System.err.println(field);
    PicaTagDefinition tag = new PicaTagDefinition(
      (String) field.get("pica3"),
      name,
      (boolean) field.get("repeatable"),
      false,
      (String) field.get("label")
    );
    addTag(map, tag);
  }

  return map;
}
 
Example #3
Source File: RestControllerV2IT.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
@Order(5)
void batchCreateTypeTest() {

  JSONObject entities = readJsonFile("/createEntitiesv2.json");

  given(testUserToken)
      .contentType(APPLICATION_JSON)
      .body(entities.toJSONString())
      .when()
      .post(API_V2 + "it_emx_datatypes_TypeTestv2")
      .then()
      .statusCode(RestTestUtils.CREATED)
      .body(
          "location",
          Matchers.equalTo("/api/v2/it_emx_datatypes_TypeTestv2?q=id=in=(\"55\",\"57\")"),
          "resources[0].href",
          Matchers.equalTo("/api/v2/it_emx_datatypes_TypeTestv2/55"),
          "resources[1].href",
          Matchers.equalTo("/api/v2/it_emx_datatypes_TypeTestv2/57"));
}
 
Example #4
Source File: ReconfigurationPlanConverter.java    From scheduler with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public ReconfigurationPlan fromJSON(JSONObject ob)
    throws JSONConverterException {

    JSONs.checkKeys(ob, ORIGIN_LABEL, ACTIONS_LABEL);
    final Model m = mc.fromJSON((JSONObject) ob.get(ORIGIN_LABEL));
    final ReconfigurationPlan plan = new DefaultReconfigurationPlan(m);
    for (final JSONObject json : (List<JSONObject>) ob.get(ACTIONS_LABEL)) {
        final String id =
            json.getAsString(ActionConverter.ID_LABEL);
        ActionConverter<? extends Action> ac = json3java.get(id);
        if (ac == null) {
            throw new JSONConverterException(
                "No converter for action '" + id + "'");
        }
        final Action action = ac.fromJSON(m, json);
        eventsFromJSON(json, m, action);
        plan.add(action);
    }
    return plan;
}
 
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: TelemetryEvent.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
public Builder(Class<T> builderClass)
{
  this.builderClass = builderClass;
  withTag("driver", driver);
  withTag("version", version);
  TelemetryService instance = TelemetryService.getInstance();
  withTag("telemetryServerDeployment", instance.getServerDeploymentName());
  withTag("connectionString", instance.getDriverConnectionString());
  JSONObject context = instance.getContext();
  if (context != null)
  {
    for (String key : context.keySet())
    {
      Object val = context.get(key);
      if (val != null)
      {
        withTag("ctx_" + key.toLowerCase(), val.toString());
      }
    }
  }
}
 
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: Persister4CollectorAPI.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("/genJsonTweetIds")
  public Response generateTweetsIDSJSONFromAllJSON(@QueryParam("collectionCode") String collectionCode,
  			@DefaultValue("true") @QueryParam("downloadLimited") Boolean downloadLimited,
  			@DefaultValue(DownloadType.TEXT_JSON) @QueryParam("jsonType") String jsonType) throws UnknownHostException {
      logger.info("Received request for collection: " + collectionCode + " with jsonType = " + jsonType);
  	JsonDeserializer jsonD = new JsonDeserializer();
  	Map<String, Object> result = jsonD.generateJson2TweetIdsJson(collectionCode, downloadLimited, DownloadJsonType.getDownloadJsonTypeFromString(jsonType));
      String fileName = PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.PERSISTER_DOWNLOAD_URL) + collectionCode+"/" + (String)result.get("fileName");
      logger.info("Done processing request for collection: " + collectionCode + ", returning created file: " + fileName);
      //return Response.ok(fileName).build();
      JSONObject obj = new JSONObject();
if ((Integer) result.get("count") < Integer.parseInt(PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.DEFAULT_TWEETID_VOLUME_LIMIT))) {
	obj.putAll(ResultStatus.getUIWrapper(collectionCode, null, fileName, true));
	logger.info("Returning JSON object: " + ResultStatus.getUIWrapper(collectionCode, null, fileName, true));
	return Response.ok(obj.toJSONString()).build();
} else {
	obj.putAll(ResultStatus.getUIWrapper(collectionCode,  PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_PREFIX) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.DEFAULT_TWEETID_VOLUME_LIMIT) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_SUFFIX), fileName, true));
	logger.info("Returning JSON object: " + ResultStatus.getUIWrapper(collectionCode,   PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_PREFIX) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.DEFAULT_TWEETID_VOLUME_LIMIT) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_SUFFIX), fileName, true));
	return Response.ok(obj.toJSONString()).build();
}
  }
 
Example #9
Source File: Persister4TaggerAPI.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/genTweetIds")
public Response generateTweetsIDSCSVFromAllJSON(@QueryParam("collectionCode") String collectionCode,
		@DefaultValue("true") @QueryParam("downloadLimited") Boolean downloadLimited) throws UnknownHostException {
	logger.debug("In tagger-persister genTweetIds");
	logger.info("received request for collection: " + collectionCode);

	JsonDeserializer jsonD = new JsonDeserializer();
	Map<String, Object> result = jsonD.generateClassifiedJson2TweetIdsCSV(collectionCode, downloadLimited);
	String fileName = PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.PERSISTER_DOWNLOAD_URL) + collectionCode + "/" + (String) result.get("fileName");

	logger.info("Done processing request for collection: " + collectionCode + ", returning created file: " + fileName);
	//return Response.ok(fileName).build();
	JSONObject obj = new JSONObject();
	if ((Integer) result.get("count") < Integer.parseInt(PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.DEFAULT_TWEETID_VOLUME_LIMIT))) {
		obj.putAll(ResultStatus.getUIWrapper(collectionCode, PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.PERSISTER_CHANGE_NOTIFY_MSG), fileName, true));
		logger.info("Returning JSON object: " + ResultStatus.getUIWrapper(collectionCode, PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.PERSISTER_CHANGE_NOTIFY_MSG), fileName, true));
		return Response.ok(obj.toJSONString()).build();
	} else {
		obj.putAll(ResultStatus.getUIWrapper(collectionCode,  PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_PREFIX) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.DEFAULT_TWEETID_VOLUME_LIMIT)+ PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_SUFFIX) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.PERSISTER_CHANGE_NOTIFY_MSG), fileName, true));
		logger.info("Returning JSON object: " + ResultStatus.getUIWrapper(collectionCode,  PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_PREFIX) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.DEFAULT_TWEETID_VOLUME_LIMIT)+ PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_SUFFIX) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.PERSISTER_CHANGE_NOTIFY_MSG), fileName, true));
		return Response.ok(obj.toJSONString()).build();
	}
}
 
Example #10
Source File: MCDResourcesInstaller.java    From mclauncher-api with MIT License 6 votes vote down vote up
/**
 * Installs resources for given version
 * @param version Version to install resources for
 * @param progress ProgressMonitor
 * @throws Exception Connection and I/O errors
 */
void installAssetsForVersion(MCDownloadVersion version, IProgressMonitor progress) throws Exception {
    // let's see which asset index is needed by this version
    Artifact index = version.getAssetIndex();
    String indexName = version.getAssetsIndexName();
    MCLauncherAPI.log.fine("Installing asset index ".concat(indexName));
    File indexDest = new File(indexesDir, indexName + ".json");
    // download this asset index
    if (!indexDest.exists() || indexDest.length() == 0)
        FileUtils.downloadFileWithProgress(index.getUrl(), indexDest, progress);
    // parse it from JSON
    FileReader fileReader = new FileReader(indexDest);
    JSONObject jsonAssets = (JSONObject) JSONValue.parse(fileReader);
    fileReader.close();
    AssetIndex assets = AssetIndex.fromJson(indexName, jsonAssets);
    // and download individual assets inside it
    downloadAssetList(assets, progress);
    MCLauncherAPI.log.fine("Finished installing asset index ".concat(indexName));
}
 
Example #11
Source File: RpcServerHandler.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
@Override
protected JSONObject processRequest(JSONRPC2Request req, MessageContext ctx)
  throws Exception
{
  JSONObject reply = new JSONObject();

  BalanceInfo bi = client.getBalance();

  reply.put("flake_confirmed", bi.getConfirmed());
  reply.put("flake_unconfirmed", bi.getUnconfirmed());
  reply.put("flake_spendable", bi.getSpendable());

  reply.put("confirmed", bi.getConfirmed() / Globals.SNOW_VALUE_D);
  reply.put("unconfirmed", bi.getUnconfirmed() / Globals.SNOW_VALUE_D);
  reply.put("spendable", bi.getSpendable() / Globals.SNOW_VALUE_D);

  return reply;
 
}
 
Example #12
Source File: RpcServerHandler.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
@Override
protected JSONObject processRequest(JSONRPC2Request req, MessageContext ctx)
  throws Exception
{
  JSONObject reply = new JSONObject();
  Map<String, Object> params = req.getNamedParams();

  String tx_data = (String)params.get("tx_data");
  Transaction tx = Transaction.parseFrom( HexUtil.hexStringToBytes(tx_data) );

  TransactionInner inner = TransactionUtil.getInner(tx);

  client.sendOrException(tx);
  reply.put("broadcast", true);

  reply.put("tx_hash", HexUtil.getHexString(tx.getTxHash()));
  reply.put("tx_data", HexUtil.getHexString(tx.toByteString()));
  reply.put("fee", inner.getFee());

  return reply;
 
}
 
Example #13
Source File: ConfigurationController.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/data-dictionary", method = {RequestMethod.PUT})
@ResponseBody
public void updateDataDictionary(@RequestBody JSONObject model) {
    try {
        DataDictionaryType dictionary = getDataDictionary(model.get("id").toString());
        String type;
        if (dictionary instanceof XpathDataDictionaryModel) {
            type = "xpath";
        } else if (dictionary instanceof XmlDataDictionaryModel) {
            type = "xml";
        } else if (dictionary instanceof JsonDataDictionaryModel) {
            type = "json";
        } else {
            throw new ApplicationRuntimeException("Unsupported data-dictionary type: " + dictionary.getClass());
        }

        DataDictionaryType component = getDataDictionaryType(type, model);
        if (projectService.hasSpringXmlApplicationContext()) {
            springBeanService.updateBeanDefinition(projectService.getSpringXmlApplicationContextFile(), projectService.getActiveProject(), component.getId(), component);
        } else if (projectService.hasSpringJavaConfig()) {
            springJavaConfigService.updateBeanDefinition(projectService.getSpringJavaConfigFile(), projectService.getActiveProject(), component.getId(), component);
        }
    } catch (IOException e) {
        throw new ApplicationRuntimeException("Failed to read data dictionary model", e);
    }
}
 
Example #14
Source File: SecretDetectorTest.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testMaskJsonObject()
{
  final String connStr =
      "https://snowflake.fakehostname.local:fakeport?LOGINTIMEOUT=20&ACCOUNT=fakeaccount&PASSWORD=fakepassword&USER=fakeuser";
  final String maskedConnStr =
      "https://snowflake.fakehostname.local:fakeport?LOGINTIMEOUT=20&ACCOUNT=fakeaccount&PASSWORD=****";

  JSONObject obj = generateJsonObject();
  obj.put("connStr", connStr);
  JSONObject maskedObj = generateJsonObject();
  maskedObj.put("connStr", maskedConnStr);

  assertThat("JSONObject is not masked successfully",
             maskedObj.equals(SecretDetector.maskJsonObject(obj)));

  obj.put("connStr", connStr);
  JSONObject nestedObj = generateJsonObject();
  nestedObj.put("subJson", obj);
  JSONObject maskedNestedObj = generateJsonObject();
  maskedNestedObj.put("subJson", maskedObj);

  assertThat("nested JSONObject is not masked successfully",
             maskedNestedObj.equals(SecretDetector.maskJsonObject(nestedObj)));
}
 
Example #15
Source File: Iso8601MessageParser.java    From secor with Apache License 2.0 6 votes vote down vote up
@Override
public long extractTimestampMillis(final Message message) {
    JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload());
    Object fieldValue = jsonObject != null ? getJsonFieldValue(jsonObject) : null;

    if (m_timestampRequired && fieldValue == null) {
        throw new RuntimeException("Missing timestamp field for message: " + message);
    }

    if (fieldValue != null) {
        try {
            Date dateFormat = DatatypeConverter.parseDateTime(fieldValue.toString()).getTime();
            return dateFormat.getTime();
        } catch (IllegalArgumentException ex) {
            if (m_timestampRequired){
                throw new RuntimeException("Bad timestamp field for message: " + message);
            }
        }
    }

    return 0;
}
 
Example #16
Source File: TestCase.java    From scheduler with GNU Lesser General Public License v3.0 6 votes vote down vote up
public String toJSON() throws JSONConverterException {
    InstanceConverter ic = new InstanceConverter();
    ic.getConstraintsConverter().register(new ScheduleConverter());
    ReconfigurationPlanConverter pc = new ReconfigurationPlanConverter();
    JSONObject o = new JSONObject();
    o.put("constraint", constraint().id());
    JSONArray a = new JSONArray();
    for (Constant c : args()) {
        a.add(c.toJSON());
    }
    o.put("args", a);
    o.put("continuous", continuous());
    o.put("groups", groups());
    o.put("plan", pc.toJSON(plan()));
    o.put("instance", ic.toJSON(instance()));
    return o.toJSONString();
}
 
Example #17
Source File: GetTagDataStatistics.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param crisisCode
 * @param attributeCode
 * @param granularity
 * @param startTime
 * @return Count sum per label from startTime to current time at the given granularity, for crisisCode and attributeCode
 */
@GET
@Path("/getlabelsum/{crisisCode}/{attributeCode}/{granularity}")
@Produces(MediaType.APPLICATION_JSON)
public Response getTagCountSumFromTime(@PathParam("crisisCode") String crisisCode,
		@PathParam("attributeCode") String attributeCode,
		@PathParam("granularity") Long granularity,
		@DefaultValue("0") @QueryParam("startTime") Long startTime) {
	
	JSONObject json = tagDataService.getTagCountSumFromTime(crisisCode, attributeCode, granularity, startTime);
	return Response.ok(json.toJSONString()).build();
}
 
Example #18
Source File: TestUtf8.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
public void testInputStream() throws Exception {
	for (String nonLatinText : nonLatinTexts) {
		String s = "{\"key\":\"" + nonLatinText + "\"}";
		ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes("utf8"));
		JSONObject obj = (JSONObject) JSONValue.parse(bis);
		String v = (String) obj.get("key"); // result is incorrect
		assertEquals(v, nonLatinText);
	}
}
 
Example #19
Source File: DeserializableEntityMessageConverterTest.java    From nem.deploy with MIT License 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void writeIsUnsupported() throws Exception {
	// Arrange:
	final MediaType supportedType = new MediaType("application", "json");
	final DeserializableEntityMessageConverter mc = createMessageConverter();
	final JsonDeserializer deserializer = new JsonDeserializer(new JSONObject(), new DeserializationContext(null));

	// Act:
	mc.write(deserializer, supportedType, new MockHttpOutputMessage());
}
 
Example #20
Source File: MosaicDefinitionCreationTransactionTest.java    From nem.core with MIT License 5 votes vote down vote up
private static void assertCannotDeserializeWithMissingProperty(final String propertyName) {
	// Arrange:
	final MosaicDefinitionCreationTransaction transaction = createTransaction();
	final JSONObject jsonObject = JsonSerializer.serializeToJson(transaction.asNonVerifiable());
	jsonObject.remove(propertyName);
	final JsonDeserializer deserializer = new JsonDeserializer(jsonObject, new DeserializationContext(new MockAccountLookup()));
	deserializer.readInt("type");

	// Assert:
	ExceptionAssert.assertThrows(
			v -> new MosaicDefinitionCreationTransaction(VerifiableEntity.DeserializationOptions.NON_VERIFIABLE, deserializer),
			MissingRequiredPropertyException.class);
}
 
Example #21
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 #22
Source File: ClientChainData.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
private boolean verifyChain(List<String> chains) throws Exception {

        PublicKey lastKey = null;
        boolean mojangKeyVerified = false;
        for (String chain: chains) {
            JWSObject jws = JWSObject.parse(chain);

            if (!mojangKeyVerified) {
                // First chain should be signed using Mojang's private key. We'd be in big trouble if it leaked...
                mojangKeyVerified = verify(MOJANG_PUBLIC_KEY, jws);
            }

            if (lastKey != null) {
                if (!verify(lastKey, jws)) {
                    throw new JOSEException("Unable to verify key in chain.");
                }
            }

            JSONObject payload = jws.getPayload().toJSONObject();
            String base64key = payload.getAsString("identityPublicKey");
            if (base64key == null) {
                throw new RuntimeException("No key found");
            }
            lastKey = generateKey(base64key);
        }
        return mojangKeyVerified;
    }
 
Example #23
Source File: QuarantineConverter.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public JSONObject toJSON(Quarantine o) {
    JSONObject c = new JSONObject();
    c.put("id", getJSONId());
    c.put("node", JSONs.elementToJSON(o.getInvolvedNodes().iterator().next()));
    return c;
}
 
Example #24
Source File: JWTUtils.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static JWToken issue(String subject, String keyId, PrivateKey privateKey, Long expires) throws JOSEException {

        JSONObject payload = new JSONObject();
        JWSHeader header = new JWSHeader(JWSAlgorithm.RS256, JOSEObjectType.JWT, null, null, null, null, null, null, null, null, keyId, null, null);
        payload.put("sub", subject);
        payload.put("exp", expires);
        JWSObject jwsObject = new JWSObject(header, new Payload(payload));
        jwsObject.sign(new RSASSASigner(privateKey));
        return new JWToken(jwsObject.serialize());
    }
 
Example #25
Source File: GetTagDataStatisticsService.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
public JSONObject getTagCountSumByGranularity(String crisisCode, Long startTime) {
	List<Long> gList = tagDataEJB.getGranularitiesForCrisis(crisisCode);
	Map<String, Long> countList = tagDataEJB.getTagCountByCrisisGranularity(crisisCode, startTime);
	JSONObject json = new JSONObject();
	json.put("crisisCode", crisisCode);
	json.put("startTime", startTime);
	if (gList != null) {
		json.put("granularities", gList);
		json.put("data", countList);
	}
	return json;
}
 
Example #26
Source File: JsonService.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
private String generateResultingJsonString(char wrappingQuote, Map<String, Object> jsonMap) {
    JSONObject jsonObject = new JSONObject(jsonMap);
    String newJson = jsonObject.toJSONString(JSONStyle.LT_COMPRESS);

    if ((!jsonObject.isEmpty()) && (newJson.charAt(1) != wrappingQuote)) {
        return replaceUnescapedOccurrencesOfCharacterInText(newJson, newJson.charAt(1), wrappingQuote);
    }

    return newJson;
}
 
Example #27
Source File: StaticRoutingConverter.java    From scheduler with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Convert a nodes map (a pair of two distinguishable nodes to source and destination) into a JSON object
 *
 * @param nm the nodes map to convert
 * @return the nodes map JSON object
 */
public JSONObject nodesMapToJSON(StaticRouting.NodesMap nm) {
    JSONObject o = new JSONObject();
    o.put("src", nm.getSrc().id());
    o.put("dst", nm.getDst().id());
    return o;
}
 
Example #28
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;
}
 
Example #29
Source File: ForgeryUtils.java    From ProxyPass with GNU Affero General Public License v3.0 5 votes vote down vote up
public static SignedJWT forgeAuthData(KeyPair pair, JSONObject extraData) {
    String publicKeyBase64 = Base64.getEncoder().encodeToString(pair.getPublic().getEncoded());
    URI x5u = URI.create(publicKeyBase64);

    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.ES384).x509CertURL(x5u).build();

    long timestamp = System.currentTimeMillis();
    Date nbf = new Date(timestamp - TimeUnit.SECONDS.toMillis(1));
    Date exp = new Date(timestamp + TimeUnit.DAYS.toMillis(1));

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .notBeforeTime(nbf)
            .expirationTime(exp)
            .issueTime(exp)
            .issuer("self")
            .claim("certificateAuthority", true)
            .claim("extraData", extraData)
            .claim("identityPublicKey", publicKeyBase64)
            .build();

    SignedJWT jwt = new SignedJWT(header, claimsSet);

    try {
        EncryptionUtils.signJwt(jwt, (ECPrivateKey) pair.getPrivate());
    } catch (JOSEException e) {
        throw new RuntimeException(e);
    }

    return jwt;
}
 
Example #30
Source File: AmountTest.java    From nem.core with MIT License 5 votes vote down vote up
@Test
public void canWriteAmount() {
	// Arrange:
	final JsonSerializer serializer = new JsonSerializer();
	final Amount amount = new Amount(0x7712411223456L);

	// Act:
	Amount.writeTo(serializer, "Amount", amount);

	// Assert:
	final JSONObject object = serializer.getObject();
	Assert.assertThat(object.size(), IsEqual.equalTo(1));
	Assert.assertThat(object.get("Amount"), IsEqual.equalTo(0x7712411223456L));
}