Java Code Examples for javax.json.JsonObject#entrySet()

The following examples show how to use javax.json.JsonObject#entrySet() . 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: GenerateExtensionsJsonMojo.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private JsonObject mergeObject(JsonObject extObject, JsonObject extOverride) {
    final JsonObjectBuilder mergedObject = Json.createObjectBuilder(extObject);
    for (Map.Entry<String, JsonValue> e : extOverride.entrySet()) {
        JsonValue.ValueType tp = e.getValue().getValueType();
        if (tp == JsonValue.ValueType.OBJECT
                && extObject.containsKey(e.getKey())
                && extObject.get(e.getKey()).getValueType() == JsonValue.ValueType.OBJECT) {
            mergedObject.add(e.getKey(),
                    mergeObject(extObject.get(e.getKey()).asJsonObject(), e.getValue().asJsonObject()));
        } else if (tp == JsonValue.ValueType.ARRAY) {
            final JsonArrayBuilder newArray = Json.createArrayBuilder(e.getValue().asJsonArray());
            mergedObject.add(e.getKey(), newArray.build());
        } else {
            mergedObject.add(e.getKey(), e.getValue());
        }
    }
    return mergedObject.build();
}
 
Example 2
Source File: QueueConfiguration.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns a {@code QueueConfiguration} created from the JSON-formatted input {@code String}. The input
 * should be a simple object of key/value pairs. Valid keys are referenced in {@link #set(String, String)}.
 *
 * @param jsonString
 * @return the {@code QueueConfiguration} created from the JSON-formatted input {@code String}
 */
public static QueueConfiguration fromJSON(String jsonString) {
   JsonObject json = JsonLoader.createReader(new StringReader(jsonString)).readObject();

   // name is the only required value
   if (!json.keySet().contains(NAME)) {
      return null;
   }
   QueueConfiguration result = new QueueConfiguration(json.getString(NAME));

   for (Map.Entry<String, JsonValue> entry : json.entrySet()) {
      result.set(entry.getKey(), entry.getValue().getValueType() == JsonValue.ValueType.STRING ? ((JsonString)entry.getValue()).getString() : entry.getValue().toString());
   }

   return result;
}
 
Example 3
Source File: TwitterStatusListener.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void onStatus(Status status) {		
	task.setSourceOutage(false);
	String json = TwitterObjectFactory.getRawJSON(status);
	JsonObject originalDoc = Json.createReader(new StringReader(json)).readObject();
	for (Predicate<JsonObject> filter : filters) {
		if (!filter.test(originalDoc)) {
			//logger.info(originalDoc.get("text").toString() + ": failed on filter = " + filter.getFilterName());
			return;
		}
	}
	JsonObjectBuilder builder = Json.createObjectBuilder();
	for (Entry<String, JsonValue> entry: originalDoc.entrySet())
		builder.add(entry.getKey(), entry.getValue());
	builder.add("aidr", aidr);
	JsonObject doc = builder.build();
	for (Publisher p : publishers)
		p.publish(channelName, doc);			
}
 
Example 4
Source File: JsonWebPage.java    From charles with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public JsonObject toJsonObject() throws JsonProcessingException {
    ObjectMapper jsonMapper = new ObjectMapper();
    jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);
    JsonReader reader = Json.createReader(
                            new StringReader(
                                jsonMapper.writeValueAsString(page)
                            )
                        );
    JsonObject parsed =  reader.readObject();
    reader.close();
    JsonObjectBuilder job = Json.createObjectBuilder();
    job.add("id", page.getUrl());
    
for (Entry<String, JsonValue> entry : parsed.entrySet()) {
    job.add(entry.getKey(), entry.getValue());
}
    return job.build();
}
 
Example 5
Source File: License.java    From sonarqube-licensecheck with Apache License 2.0 6 votes vote down vote up
/**
 * @deprecated remove with later release
 * @param serializedLicensesString setting string
 * @return a list with licences
 */
@Deprecated
private static List<License> readLegacyJson(String serializedLicensesString)
{
    List<License> licenses = new ArrayList<>();

    try (JsonReader jsonReader = Json.createReader(new StringReader(serializedLicensesString)))
    {
        JsonObject licensesJson = jsonReader.readObject();
        for (Map.Entry<String, JsonValue> licenseJson : licensesJson.entrySet())
        {
            JsonObject value = (JsonObject) licenseJson.getValue();
            licenses.add(new License(value.getString("name"), licenseJson.getKey(),
                value.getString("status")));
        }
    }

    return licenses;
}
 
Example 6
Source File: NetworkConfig.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
private Map<String, JsonObject> findCertificateAuthorities() throws NetworkConfigurationException {
    Map<String, JsonObject> ret = new HashMap<>();

    JsonObject jsonCertificateAuthorities = getJsonObject(jsonConfig, "certificateAuthorities");
    if (null != jsonCertificateAuthorities) {

        for (Entry<String, JsonValue> entry : jsonCertificateAuthorities.entrySet()) {
            String name = entry.getKey();

            JsonObject jsonCA = getJsonValueAsObject(entry.getValue());
            if (jsonCA == null) {
                throw new NetworkConfigurationException(format("Error loading config. Invalid CA entry: %s", name));
            }
            ret.put(name, jsonCA);
        }
    }

    return ret;

}
 
Example 7
Source File: NetworkConfig.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void createAllPeers() throws NetworkConfigurationException {

        // Sanity checks
        if (peers != null) {
            throw new NetworkConfigurationException("INTERNAL ERROR: peers have already been initialized!");
        }

        peers = new HashMap<>();

        // peers is a JSON object containing a nested object for each peer
        JsonObject jsonPeers = getJsonObject(jsonConfig, "peers");

        //out("Peers: " + (jsonPeers == null ? "null" : jsonPeers.toString()));
        if (jsonPeers != null) {

            for (Entry<String, JsonValue> entry : jsonPeers.entrySet()) {
                String peerName = entry.getKey();

                JsonObject jsonPeer = getJsonValueAsObject(entry.getValue());
                if (jsonPeer == null) {
                    throw new NetworkConfigurationException(format("Error loading config. Invalid peer entry: %s", peerName));
                }

                Node peer = createNode(peerName, jsonPeer, "url");
                if (peer == null) {
                    throw new NetworkConfigurationException(format("Error loading config. Invalid peer entry: %s", peerName));
                }
                peers.put(peerName, peer);

            }
        }

    }
 
Example 8
Source File: ApiStart2.java    From logbook-kai with MIT License 5 votes vote down vote up
/**
 * store
 * 
 * @param obj api_data
 */
private void store(JsonObject root) {
    if (AppConfig.get().isStoreApiStart2()) {
        try {
            String dir = AppConfig.get().getStoreApiStart2Dir();
            if (dir == null || "".equals(dir))
                return;

            Path dirPath = Paths.get(dir);
            Path parent = dirPath.getParent();
            if (parent != null && !Files.exists(parent)) {
                Files.createDirectories(parent);
            }

            JsonWriterFactory factory = Json
                    .createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true));
            for (Entry<String, JsonValue> entry : root.entrySet()) {
                String key = entry.getKey();
                JsonValue val = entry.getValue();
                JsonObject obj = Json.createObjectBuilder().add(key, val).build();

                Path outPath = dirPath.resolve(key + ".json");

                try (OutputStream out = Files.newOutputStream(outPath)) {
                    try (JsonWriter writer = factory.createWriter(out)) {
                        writer.write(obj);
                    }
                }
            }
        } catch (Exception e) {
            LoggerHolder.get().warn("api_start2の保存に失敗しました", e);
        }
    }
}
 
Example 9
Source File: NetworkConfig.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private static Properties extractProperties(JsonObject json, String fieldName) {
    Properties props = new Properties();

    // Extract any other grpc options
    JsonObject options = getJsonObject(json, fieldName);
    if (options != null) {

        for (Entry<String, JsonValue> entry : options.entrySet()) {
            String key = entry.getKey();
            JsonValue value = entry.getValue();
            props.setProperty(key, getJsonValue(value));
        }
    }
    return props;
}
 
Example 10
Source File: NetworkConfig.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void createAllOrganizations(Map<String, JsonObject> foundCertificateAuthorities) throws NetworkConfigurationException {

        // Sanity check
        if (organizations != null) {
            throw new NetworkConfigurationException("INTERNAL ERROR: organizations have already been initialized!");
        }

        organizations = new HashMap<>();

        // organizations is a JSON object containing a nested object for each Org
        JsonObject jsonOrganizations = getJsonObject(jsonConfig, "organizations");

        if (jsonOrganizations != null) {

            for (Entry<String, JsonValue> entry : jsonOrganizations.entrySet()) {
                String orgName = entry.getKey();

                JsonObject jsonOrg = getJsonValueAsObject(entry.getValue());
                if (jsonOrg == null) {
                    throw new NetworkConfigurationException(format("Error loading config. Invalid Organization entry: %s", orgName));
                }

                OrgInfo org = createOrg(orgName, jsonOrg, foundCertificateAuthorities);
                organizations.put(orgName, org);
            }
        }

    }
 
Example 11
Source File: GraphQLVariables.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> toMap(JsonObject jo) {
    Map<String, Object> ro = new HashMap<>();
    if (jo != null) {
        Set<Map.Entry<String, JsonValue>> entrySet = jo.entrySet();
        for (Map.Entry<String, JsonValue> es : entrySet) {
            ro.put(es.getKey(), toObject(es.getValue()));
        }
    }
    return ro;
}
 
Example 12
Source File: NetworkConfig.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private void createAllOrderers() throws NetworkConfigurationException {

        // Sanity check
        if (orderers != null) {
            throw new NetworkConfigurationException("INTERNAL ERROR: orderers have already been initialized!");
        }

        orderers = new HashMap<>();

        // orderers is a JSON object containing a nested object for each orderers
        JsonObject jsonOrderers = getJsonObject(jsonConfig, "orderers");

        if (jsonOrderers != null) {

            for (Entry<String, JsonValue> entry : jsonOrderers.entrySet()) {
                String ordererName = entry.getKey();

                JsonObject jsonOrderer = getJsonValueAsObject(entry.getValue());
                if (jsonOrderer == null) {
                    throw new NetworkConfigurationException(format("Error loading config. Invalid orderer entry: %s", ordererName));
                }

                Node orderer = createNode(ordererName, jsonOrderer, "url");
                if (orderer == null) {
                    throw new NetworkConfigurationException(format("Error loading config. Invalid orderer entry: %s", ordererName));
                }
                orderers.put(ordererName, orderer);
            }
        }

    }
 
Example 13
Source File: JsonUtil.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new object builder.
 * @param jso the object used to populate the builder
 * @return the builder
 */
public static JsonObjectBuilder newObjectBuilder(JsonObject jso) {
  JsonObjectBuilder jb = Json.createObjectBuilder();
  if (jso != null) {
    for (Entry<String, JsonValue> entry: jso.entrySet()) {
      jb.add(entry.getKey(), entry.getValue());
    }
  }
  return jb;
}
 
Example 14
Source File: WebHCatJsonParser.java    From hadoop-etl-udfs with MIT License 5 votes vote down vote up
public static List<HCatSerDeParameter> parseSerDeParameters(String json) throws Exception {
    assert(!(json == null) && !json.isEmpty());
    JsonObject obj = JsonUtil.getJsonObject(json);
    List<HCatSerDeParameter> serDeParameters = new ArrayList<>();
    for (Entry<String, JsonValue> param : obj.entrySet()) {
        assert(param.getValue().getValueType() == ValueType.STRING);
        serDeParameters.add(new HCatSerDeParameter(param.getKey(), ((JsonString)param.getValue()).getString()));
    }
    return serDeParameters;
}
 
Example 15
Source File: WebHCatJsonParser.java    From hadoop-etl-udfs with MIT License 5 votes vote down vote up
public static List<HCatSerDeParameter> parseSerDeParameters(JsonObject obj) {
    List<HCatSerDeParameter> serDeParameters = new ArrayList<>();
    for (Entry<String, JsonValue> serdeParam : obj.entrySet()) {
        assert(serdeParam.getValue().getValueType() == ValueType.STRING);
        serDeParameters.add(new HCatSerDeParameter(serdeParam.getKey(), ((JsonString)serdeParam.getValue()).getString()));
    }
    return serDeParameters;
}
 
Example 16
Source File: FeatureServiceImpl.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private FeatureBundle[] getBundles(JsonObject json) {
    JsonArray ja = json.getJsonArray("bundles");
    if (ja == null)
        return new FeatureBundle[] {};

    List<FeatureBundle> bundles = new ArrayList<>();

    for (JsonValue val : ja) {
        if (val.getValueType() == JsonValue.ValueType.OBJECT) {
            JsonObject jo = val.asJsonObject();
            String bid = jo.getString("id");
            FeatureBundleBuilder builder = builderFactory.newBundleBuilder(ID.fromMavenID(bid));

            for (Map.Entry<String, JsonValue> entry : jo.entrySet()) {
                if (entry.getKey().equals("id"))
                    continue;

                JsonValue value = entry.getValue();

                Object v;
                switch (value.getValueType()) {
                case NUMBER:
                    v = ((JsonNumber) value).longValueExact();
                    break;
                case STRING:
                    v = ((JsonString) value).getString();
                    break;
                default:
                    v = value.toString();
                }
                builder.addMetadata(entry.getKey(), v);
            }
            bundles.add(builder.build());
        }
    }

    return bundles.toArray(new FeatureBundle[0]);
}
 
Example 17
Source File: FeatureServiceImpl.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
private FeatureExtension[] getExtensions(JsonObject json) {
    JsonObject jo = json.getJsonObject("extensions");
    if (jo == null)
        return new FeatureExtension[] {};

    List<FeatureExtension> extensions = new ArrayList<>();

    for (Map.Entry<String,JsonValue> entry : jo.entrySet()) {
        JsonObject exData = entry.getValue().asJsonObject();
        FeatureExtension.Type type;
        if (exData.containsKey("text")) {
            type = FeatureExtension.Type.TEXT;
        } else if (exData.containsKey("artifacts")) {
            type = FeatureExtension.Type.ARTIFACTS;
        } else if (exData.containsKey("json")) {
            type = FeatureExtension.Type.JSON;
        } else {
            throw new IllegalStateException("Invalid extension: " + entry);
        }
        String k = exData.getString("kind", "optional");
        FeatureExtension.Kind kind = FeatureExtension.Kind.valueOf(k.toUpperCase());

        FeatureExtensionBuilder builder = builderFactory.newExtensionBuilder(entry.getKey(), type, kind);

        switch (type) {
        case TEXT:
            builder.addText(exData.getString("text"));
            break;
        case ARTIFACTS:
            JsonArray ja2 = exData.getJsonArray("artifacts");
            for (JsonValue jv : ja2) {
                if (jv.getValueType() == JsonValue.ValueType.STRING) {
                    String id = ((JsonString) jv).getString();
                    builder.addArtifact(ID.fromMavenID(id));
                }
            }
            break;
        case JSON:
            builder.setJSON(exData.getJsonObject("json").toString());
            break;
        }
        extensions.add(builder.build());
    }

    return extensions.toArray(new FeatureExtension[] {});
}
 
Example 18
Source File: MigrationService.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@Override
public JsonObject migrate( final JsonObject state, String toVersion, StateStore stateStore )
    throws JsonException
{
    // Get current version
    String fromVersion = state.getString( JSONKeys.APPLICATION_VERSION, "0.0" );

    Iterable<EntityMigrationRule> matchedRules = builder.entityMigrationRules()
                                                        .rulesBetweenVersions( fromVersion, toVersion );

    JsonObject migratedState = state;
    boolean changed = false;
    List<String> failures = new ArrayList<>();
    if( matchedRules != null )
    {
        for( EntityMigrationRule matchedRule : matchedRules )
        {
            MigrationContext context = new MigrationContext();

            migratedState = matchedRule.upgrade( context, migratedState, stateStore, migrator );

            if( context.isSuccess() && context.hasChanged() && LOGGER.isDebugEnabled() )
            {
                LOGGER.debug( matchedRule.toString() );
            }

            failures.addAll( context.failures() );
            changed = context.hasChanged() || changed;
        }
    }

    JsonObjectBuilder appVersionBuilder = jsonFactories.builderFactory().createObjectBuilder();
    for( Map.Entry<String, JsonValue> entry : migratedState.entrySet() )
    {
        appVersionBuilder.add( entry.getKey(), entry.getValue() );
    }
    appVersionBuilder.add( JSONKeys.APPLICATION_VERSION, toVersion );
    migratedState = appVersionBuilder.build();

    if( failures.size() > 0 )
    {
        LOGGER.warn( "Migration of {} from {} to {} aborted, failed operation(s):\n{}",
                     state.getString( JSONKeys.IDENTITY ), fromVersion, toVersion,
                     String.join( "\n\t", failures ) );
        return state;
    }

    if( changed )
    {
        LOGGER.info( "Migrated {} from {} to {}",
                     migratedState.getString( JSONKeys.IDENTITY ), fromVersion, toVersion );
        return migratedState;
    }

    // Nothing done
    return state;
}
 
Example 19
Source File: NetworkMessageEvent.java    From vicinity-gateway-api with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Takes the JSON object and fills necessary fields with values.
 * 
 * @param json JSON to parse.
 * @return True if parsing was successful, false otherwise.
 */
private boolean parseJson(JsonObject json){
	
	// first check out whether or not the message has everything it is supposed to have and stop if not
	if (
			!json.containsKey(ATTR_MESSAGETYPE) ||
			!json.containsKey(ATTR_SOURCEOID) ||
			!json.containsKey(ATTR_EVENTID) ||
			!json.containsKey(ATTR_EVENTBODY) ||
			!json.containsKey(ATTR_PARAMETERS)) {
		
		return false;
	}
	
	// prepare objects for parameters and attributes
	JsonObject parametersJson = null;
	
	// load values from JSON
	try {
		
		messageType = json.getInt(NetworkMessage.ATTR_MESSAGETYPE);
		
		// null values are special cases in JSON, they get transported as "null" string and must be treated
		// separately 
		if (!json.isNull(ATTR_SOURCEOID)) {
			sourceOid = json.getString(ATTR_SOURCEOID);
		}
		
		if (!json.isNull(ATTR_EVENTID)) {
			eventId = json.getString(ATTR_EVENTID);
		}
		
		if (!json.isNull(ATTR_EVENTBODY)) {
			eventBody = json.getString(ATTR_EVENTBODY);
		}
		
		if (!json.isNull(ATTR_PARAMETERS)) {
			parametersJson = json.getJsonObject(ATTR_PARAMETERS);
		}
		
		if (!json.isNull(ATTR_REQUESTID)) {
			requestId = json.getInt(ATTR_REQUESTID);
		}
		
	} catch (Exception e) {
		logger.severe("NetworkMessageEvent: Exception while parsing NetworkMessageEvent: " + e.getMessage());
		
		return false;
	}
	
	// process non primitives, start with strings
	
	sourceOid = removeQuotes(sourceOid);
	eventId = removeQuotes(eventId);
	eventBody = removeQuotes(eventBody);
	
	// important
	if (sourceOid == null || eventId == null) {
		return false;
	}
	 
	// here the parameters will be stored during reading
	Set<Entry<String,JsonValue>> entrySet;
	String stringValue;
			
	// this can be null, but that should not be dangerous. we'll just leave the set clear in such case
	if (parametersJson != null){
		
		entrySet = parametersJson.entrySet();
		for (Entry<String, JsonValue> entry : entrySet) {

			// we have to remove the quotes
			stringValue = removeQuotes(entry.getValue().toString());
			
			// and the null value got transported more like string... we have to make a rule for it
			if (stringValue.equals("null")){
				parameters.put(entry.getKey(), null);
			} else {
				parameters.put(entry.getKey(), stringValue);
			}
		}
	}
	
	return true;
}
 
Example 20
Source File: ApiServiceDispatcher.java    From iaf with Apache License 2.0 4 votes vote down vote up
private JsonObjectBuilder mapResponses(IAdapter adapter, MediaTypes contentType, JsonObjectBuilder schemas) {
	JsonObjectBuilder responses = Json.createObjectBuilder();

	PipeLine pipeline = adapter.getPipeLine();
	Json2XmlValidator validator = getJsonValidator(pipeline);
	JsonObjectBuilder schema = null;
	if(validator != null) {
		JsonObject jsonSchema = validator.createJsonSchemaDefinitions("#/components/schemas/");
		if(jsonSchema != null) {
			for (Entry<String,JsonValue> entry: jsonSchema.entrySet()) {
				schemas.add(entry.getKey(), entry.getValue());
			}
			String ref = validator.getMessageRoot(true);
			schema = Json.createObjectBuilder();
			schema.add("schema", Json.createObjectBuilder().add("$ref", "#/components/schemas/"+ref));
		}
	}

	Map<String, PipeLineExit> pipeLineExits = pipeline.getPipeLineExits();
	for(String exitPath : pipeLineExits.keySet()) {
		PipeLineExit ple = pipeLineExits.get(exitPath);
		int exitCode = ple.getExitCode();
		if(exitCode == 0) {
			exitCode = 200;
		}

		JsonObjectBuilder exit = Json.createObjectBuilder();

		Status status = Status.fromStatusCode(exitCode);
		exit.add("description", status.getReasonPhrase());
		if(!ple.getEmptyResult()) {
			JsonObjectBuilder content = Json.createObjectBuilder();
			if(schema == null) {
				content.addNull(contentType.getContentType());
			} else {
				content.add(contentType.getContentType(), schema);
			}
			exit.add("content", content);
		}

		responses.add(""+exitCode, exit);
	}
	return responses;
}