javax.json.JsonStructure Java Examples

The following examples show how to use javax.json.JsonStructure. 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: UserView.java    From javaee8-cookbook with Apache License 2.0 7 votes vote down vote up
private void loadFromStructure() {
    JsonStructure structure = BUILDERFACTORY.createObjectBuilder()
            .add("name", "User1")
            .add("email", "[email protected]")
            .add("profiles", BUILDERFACTORY.createArrayBuilder()
                    .add(BUILDERFACTORY.createObjectBuilder()
                            .add("id", "1")
                            .add("name", "Profile1"))
                    .add(BUILDERFACTORY.createObjectBuilder()
                            .add("id", "2")
                            .add("name", "Profile2")))
            .build();
    fromStructure = jsonbBuilder.toJson(structure);

    JsonPointer pointer = Json.createPointer("/profiles");
    JsonValue value = pointer.getValue(structure);
    fromJpointer = value.toString();
}
 
Example #2
Source File: XmlTypeToJsonSchemaConverter.java    From iaf with Apache License 2.0 7 votes vote down vote up
public JsonStructure createJsonSchema(String elementName, XSElementDeclaration elementDecl) {
	JsonObjectBuilder builder = Json.createObjectBuilder();
	builder.add("$schema", JSON_SCHEMA);
	if(elementDecl.getNamespace() != null){
		builder.add("$id", elementDecl.getNamespace());
	}
	if(schemaLocation != null){
		builder.add("description", "Auto-generated by Frank!Framework based on " + schemaLocation);
	}
	if (skipRootElement) {
		builder.add("$ref", definitionsPath+elementName);
	} else {
		builder.add("type", "object").add("additionalProperties", false);
		builder.add("properties", Json.createObjectBuilder().add(elementName, Json.createObjectBuilder().add("$ref", definitionsPath+elementName).build()));
	}
	JsonObject definitionsBuilderResult = getDefinitions();
	if(!definitionsBuilderResult.isEmpty()){
		builder.add("definitions", definitionsBuilderResult);
	}
	return builder.build();
}
 
Example #3
Source File: GeneratorSetJson.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the JSON object that represents the given generator.
 */
private static JsonStructure toJson( ITestCaseGenerator generator)
  {
  JsonObjectBuilder builder = Json.createObjectBuilder();

  if( generator.getClass().equals( TupleGenerator.class))
    {
    TupleGenerator tupleGenerator = (TupleGenerator) generator;
    builder.add( TUPLES_KEY, tupleGenerator.getDefaultTupleSize());
    Optional.ofNullable( tupleGenerator.getRandomSeed()).ifPresent( seed -> builder.add( SEED_KEY, seed));
    
    JsonArrayBuilder combinersBuilder = Json.createArrayBuilder();
    tupleGenerator.getCombiners().stream().forEach( combiner -> combinersBuilder.add( toJson( combiner)));
    JsonArray combiners = combinersBuilder.build();
    if( !combiners.isEmpty())
      {
      builder.add( COMBINERS_KEY, combiners);
      }
    }

  return builder.build();
  }
 
Example #4
Source File: Plugin.java    From rapid with MIT License 6 votes vote down vote up
@POST
@Path("{id}/push")
public JsonStructure pushPlugin(@PathParam("id") String id) {

    WebTarget target = resource().path("plugins").path(id).path("push");

    Response response = postResponse(target);
    String entity = response.readEntity(String.class);
    response.close();

    JsonStructure result;
    if (entity.isEmpty()) {
        result = Json.createObjectBuilder().add("message", id + " plugin pushed.").build();
    } else {
        result = Json.createReader(new StringReader(entity)).read();
    }
    return result;
}
 
Example #5
Source File: Plugin.java    From rapid with MIT License 6 votes vote down vote up
@POST
@Path("pull")
public JsonStructure pullPlugin(@QueryParam("remote") String remote,
                                @QueryParam("name") String name,
                                JsonStructure content) {

    WebTarget target = resource().path("plugins").path("pull");

    if (Objects.nonNull(remote))
        target = target.queryParam("remote", remote);
    if (Objects.nonNull(name))
        target = target.queryParam("name", name);

    Response response = postResponse(target, content);
    String entity = response.readEntity(String.class);
    response.close();

    JsonStructure result;
    if (entity.isEmpty()) {
        result = Json.createObjectBuilder().add("message", "plugin pulled.").build();
    } else {
        result = Json.createReader(new StringReader(entity)).read();
    }
    return result;
}
 
Example #6
Source File: Plugin.java    From rapid with MIT License 6 votes vote down vote up
@POST
@Path("{id}/disable")
public JsonStructure disablePlugin(@PathParam("id") String id) {

    WebTarget target = resource().path("plugins").path(id).path("disable");

    Response response = postResponse(target);
    String entity = response.readEntity(String.class);
    response.close();

    JsonStructure structure;
    if (entity.isEmpty()) {
        structure = Json.createObjectBuilder().add("message", id + " plugin disabled.").build();
    } else {
        structure = Json.createReader(new StringReader(entity)).read();
    }
    return structure;
}
 
Example #7
Source File: Plugin.java    From rapid with MIT License 6 votes vote down vote up
@POST
@Path("{id}/enable")
public JsonStructure enablePlugin(@PathParam("id") String id,
                                  @DefaultValue("0") @QueryParam("timeout") int timeout) {

    WebTarget target = resource().path("plugins").path(id).path("enable").queryParam("timeout", timeout);

    Response response = postResponse(target);
    String entity = response.readEntity(String.class);
    response.close();

    JsonStructure structure;
    if (entity.isEmpty()) {
        structure = Json.createObjectBuilder().add("message", id + " plugin enabled.").build();
    } else {
        structure = Json.createReader(new StringReader(entity)).read();
    }
    return structure;
}
 
Example #8
Source File: JavaxJsonDeserializer.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
/**
 * Map deserialization.
 *
 * {@literal JsonObject}s are deserialized to {@literal Map<String, ?>}.
 * {@literal JsonArray}s of key/value {@literal JsonObject}s are deserialized to {@literal Map<?, ?>}.
 */
private Map<?, ?> deserializeMap( ModuleDescriptor module, MapType mapType, JsonStructure json )
{
    if( json.getValueType() == JsonValue.ValueType.OBJECT )
    {
        JsonObject object = (JsonObject) json;
        return object.entrySet().stream()
                     .map( entry -> new AbstractMap.SimpleImmutableEntry<>(
                         entry.getKey(),
                         doDeserialize( module, mapType.valueType(), entry.getValue() ) ) )
                     .collect( toMapWithNullValues( LinkedHashMap::new ) );
    }
    if( json.getValueType() == JsonValue.ValueType.ARRAY )
    {
        JsonArray array = (JsonArray) json;
        return array.stream()
                    .map( JsonObject.class::cast )
                    .map( entry -> new AbstractMap.SimpleImmutableEntry<>(
                        doDeserialize( module, mapType.keyType(), entry.get( "key" ) ),
                        doDeserialize( module, mapType.valueType(), entry.get( "value" ) )
                    ) )
                    .collect( toMapWithNullValues( LinkedHashMap::new ) );
    }
    throw new SerializationException( "Don't know how to deserialize " + mapType + " from " + json );
}
 
Example #9
Source File: CodeModelJsonStructureWriter.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void writeJsonStructure(Module<NType, NClass> module,
		JsonStructure structure, String fileName) {
	try {
		final JPackage _package = codeModel._package("");
		_package.addResourceFile(createTextFile(fileName, structure));
	} catch (IOException ioex) {
		try {
			errorHandler.error(new SAXParseException(MessageFormat.format(
					"Could not create the code for the module [{0}].",
					module.getName()), null, ioex));
		} catch (SAXException ignored) {

		}
	}
}
 
Example #10
Source File: GeoJsonReader.java    From geojson with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getTags(final JsonObject feature) {
    final Map<String, String> tags = new TreeMap<>();

    if (feature.containsKey(PROPERTIES) && !feature.isNull(PROPERTIES)) {
        JsonValue properties = feature.get(PROPERTIES);
        if(properties != null && properties.getValueType().equals(JsonValue.ValueType.OBJECT)) {
            for (Map.Entry<String, JsonValue> stringJsonValueEntry : properties.asJsonObject().entrySet()) {
                final JsonValue value = stringJsonValueEntry.getValue();

                if (value instanceof JsonString) {
                    tags.put(stringJsonValueEntry.getKey(), ((JsonString) value).getString());
                } else if (value instanceof JsonStructure) {
                    Logging.warn(
                        "The GeoJSON contains an object with property '" + stringJsonValueEntry.getKey()
                            + "' whose value has the unsupported type '" + value.getClass().getSimpleName() + "'. That key-value pair is ignored!"
                    );
                } else if (value.getValueType() != JsonValue.ValueType.NULL) {
                    tags.put(stringJsonValueEntry.getKey(), value.toString());
                }
            }
        }
    }
    return tags;
}
 
Example #11
Source File: Json2Xml.java    From iaf with Apache License 2.0 6 votes vote down vote up
public static String translate(JsonStructure json, URL schemaURL, boolean compactJsonArrays, String rootElement, boolean strictSyntax, boolean deepSearch, String targetNamespace, Map<String,Object> overrideValues) throws SAXException, IOException {
	ValidatorHandler validatorHandler = getValidatorHandler(schemaURL);
	List<XSModel> schemaInformation = getSchemaInformation(schemaURL);

	// create the validator, setup the chain
	Json2Xml j2x = new Json2Xml(validatorHandler,schemaInformation,compactJsonArrays,rootElement,strictSyntax);
	if (overrideValues!=null) {
		j2x.setOverrideValues(overrideValues);
	}
	if (targetNamespace!=null) {
		//if (DEBUG) System.out.println("setting targetNamespace ["+targetNamespace+"]");
		j2x.setTargetNamespace(targetNamespace);
	}
	j2x.setDeepSearch(deepSearch);

	return j2x.translate(json);
}
 
Example #12
Source File: JsonUtil.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
/**
 * Create a JSON string.
 * @param structure the structure JsonAoject or JsonArray
 * @param pretty for pretty print
 * @return the JSON string
 */
public static String toJson(JsonStructure structure, boolean pretty) {
  JsonWriter writer  = null;
  StringWriter result = new StringWriter();
  try {
    Map<String, Object> props = new HashMap<String,Object>();
    if (pretty) props.put(JsonGenerator.PRETTY_PRINTING,true);
    JsonWriterFactory factory = Json.createWriterFactory(props);
    writer = factory.createWriter(result);
    writer.write(structure); 
  } finally {
    try {
      if (writer != null) writer.close();
    } catch (Throwable t) {
      t.printStackTrace(System.err);
    }
  }
  return result.toString().trim();
}
 
Example #13
Source File: SwaggerBackendTest.java    From jaxrs-analyzer with Apache License 2.0 6 votes vote down vote up
@Test
    public void test() {
        final Project project = new Project("project name", "1.0", resources);
        cut.configure(singletonMap(INLINE_PRETTIFY, "false"));
        final String actualOutput = new String(cut.render(project));

        // TODO to fix test w/ different formattings
//            assertEquals(expectedOutput, actualOutput);

        try (final StringReader expectedReader = new StringReader(expectedOutput);
             final StringReader actualReader = new StringReader(actualOutput)
        ) {
            final JsonStructure expected = Json.createReader(expectedReader).read();
            final JsonStructure actual = Json.createReader(actualReader).read();
            assertEquals(expected, actual);
        }
    }
 
Example #14
Source File: JsonValueResolverTest.java    From trimou with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutOfBoundIndexException() throws FileNotFoundException {
    // https://github.com/trimou/trimou/issues/73
    String json = "{\"numbers\": [1,2]}";
    String template = "One of users is {{numbers.2}}.";
    JsonStructure jsonStructure = Json.createReader(new StringReader(json))
            .read();
    MustacheEngine engine = MustacheEngineBuilder.newBuilder()
            .setMissingValueHandler(
                    new ThrowingExceptionMissingValueHandler())
            .omitServiceLoaderConfigurationExtensions()
            .setProperty(JsonValueResolver.ENABLED_KEY, true)
            .setProperty(JsonProcessingValueConverter.ENABLED_KEY, false)
            .addResolver(new ThisResolver()).addResolver(new MapResolver())
            .addResolver(new JsonValueResolver()).build();
    final Mustache mustache = engine.compileMustache("unwrap_array_index",
            template);
    MustacheExceptionAssert.expect(MustacheProblem.RENDER_NO_VALUE)
            .check(() -> mustache.render(jsonStructure));
}
 
Example #15
Source File: JsrJsonpProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadJsonObject() throws Exception {
    final StringWriter writer = new StringWriter();

    Json.createGenerator(writer)
        .writeStartObject()
        .write("firstName", "Tom")
        .write("lastName", "Tommyknocker")
        .writeEnd()
        .close();

    final String str = writer.toString();
    writer.close();

    final JsonStructure obj = provider.readFrom(JsonStructure.class, null, null, null, null,
        new ByteArrayInputStream(str.getBytes()));

    assertThat(obj, instanceOf(JsonObject.class));
    assertThat(((JsonObject)obj).getString("firstName"), equalTo("Tom"));
    assertThat(((JsonObject)obj).getString("lastName"), equalTo("Tommyknocker"));
}
 
Example #16
Source File: JsrJsonpProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadJsonArray() throws Exception {
    final StringWriter writer = new StringWriter();

    Json.createGenerator(writer)
        .writeStartArray()
        .write("Tom")
        .write("Tommyknocker")
        .writeEnd()
        .close();

    final JsonStructure obj = provider.readFrom(JsonStructure.class, null, null, null, null,
        new ByteArrayInputStream(writer.toString().getBytes()));

    assertThat(obj, instanceOf(JsonArray.class));
    assertThat(((JsonArray)obj).getString(0), equalTo("Tom"));
    assertThat(((JsonArray)obj).getString(1), equalTo("Tommyknocker"));
    assertThat(((JsonArray)obj).size(), equalTo(2));
}
 
Example #17
Source File: SystemInputJson.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the JSON object that represents the given value definition.
 */
private static JsonStructure toJson( VarValueDef value)
  {
  JsonObjectBuilder builder = Json.createObjectBuilder();

  if( value.getType().equals( FAILURE))
    {
    builder.add( FAILURE_KEY, true);
    }
  else if( value.getType().equals( ONCE))
    {
    builder.add( ONCE_KEY, true);
    }

  addAnnotations( builder, value);

  ConditionJson.toJson( value).ifPresent( json -> builder.add( WHEN_KEY, json));
    
  addProperties( builder, value);

  return builder.build();
  }
 
Example #18
Source File: Json2Xml.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
public String getNodeText(XSElementDeclaration elementDeclaration, JsonValue node) {
	String result;
	if (node instanceof JsonString) {
		result=((JsonString)node).getString();
	} else if (node instanceof JsonStructure) { // this happens when override key is present without a value
		result=null; 
	} else { 
		result=node.toString();
	}
	if ("{}".equals(result)) {
		result="";
	}
	if (log.isTraceEnabled()) log.trace("getText() node ["+ToStringBuilder.reflectionToString(node)+"] = ["+result+"]");
	return result;
}
 
Example #19
Source File: JsrJsonpProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteJsonArray() throws Exception {
    final JsonArray obj = Json.createArrayBuilder()
        .add(
            Json.createObjectBuilder()
                .add("firstName", "Tom")
                .add("lastName", "Tommyknocker")
        )
        .add(
            Json.createObjectBuilder()
                .add("firstName", "Bob")
                .add("lastName", "Bobbyknocker")
        )
        .build();

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    provider.writeTo(obj, JsonStructure.class, null, null, null, null, out);
    out.close();

    assertThat(new String(out.toByteArray()),
        equalTo("[{\"firstName\":\"Tom\",\"lastName\":\"Tommyknocker\"},"
                + "{\"firstName\":\"Bob\",\"lastName\":\"Bobbyknocker\"}]"));
}
 
Example #20
Source File: SystemInputJson.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the JSON object that represents the given variable definition.
 */
private static JsonStructure toJson( IVarDef varDef)
  {
  JsonObjectBuilder builder = Json.createObjectBuilder();

  addAnnotations( builder, varDef);

  ConditionJson.toJson( varDef).ifPresent( json -> builder.add( WHEN_KEY, json));

  if( varDef.getValues() != null)
    {
    JsonObjectBuilder valuesBuilder = Json.createObjectBuilder();
    toStream( varDef.getValues()).forEach( value -> valuesBuilder.add( String.valueOf( value.getName()), toJson( value)));
    builder.add( VALUES_KEY, valuesBuilder.build());
    }
  else if( varDef.getMembers() != null)
    {
    JsonObjectBuilder membersBuilder = Json.createObjectBuilder();
    toStream( varDef.getMembers()).forEach( member -> membersBuilder.add( member.getName(), toJson( member)));
    builder.add( MEMBERS_KEY, membersBuilder.build());
    }
    
  return builder.build();
  }
 
Example #21
Source File: JsrJsonpProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteJsonObject() throws Exception {
    final JsonObject obj = Json.createObjectBuilder()
        .add("firstName", "Tom")
        .add("lastName", "Tommyknocker")
        .build();

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    provider.writeTo(obj, JsonStructure.class, null, null, null, null, out);
    out.close();

    assertThat(new String(out.toByteArray()),
        equalTo("{\"firstName\":\"Tom\",\"lastName\":\"Tommyknocker\"}"));
}
 
Example #22
Source File: JsrJsonpProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testWritableTypes() throws Exception {
    assertThat(provider.isWriteable(JsonArray.class, null, null, null),
        equalTo(true));
    assertThat(provider.isWriteable(JsonStructure.class, null, null, null),
        equalTo(true));
    assertThat(provider.isWriteable(JsonObject.class, null, null, null),
        equalTo(true));
    assertThat(provider.isWriteable(JsonValue.class, null, null, null),
        equalTo(false));
}
 
Example #23
Source File: TestXml2Map.java    From iaf with Apache License 2.0 5 votes vote down vote up
@Override
public void testFiles(String schemaFile, String namespace, String rootElement, String inputFile, boolean potentialCompactionProblems, String expectedFailureReason) throws Exception {
	URL schemaUrl=getSchemaURL(schemaFile);
   	String xmlString=getTestFile(inputFile+".xml");
   	String mapString=getTestFile(inputFile+".properties");
   	
 
	 boolean expectValid=expectedFailureReason==null;
  	// check the validity of the input XML
   	assertEquals("valid XML", expectValid, Utils.validate(schemaUrl, xmlString));
   	
   	System.out.println("input xml:"+xmlString);
   	JsonStructure json;
   	Map<String,String> result;
   	try {
   		result=Xml2Map.translate(xmlString, schemaUrl);
    	for (String key: result.keySet()) {
    		String value=result.get(key);
    		System.out.println(key+"="+value);
    	}
    	if (!expectValid) {
			fail("expected to fail");
		}
    	if (mapString==null) {
    		fail("no .properties file for ["+inputFile+"]!");
    	}
    	assertEquals(mapString.trim(), MatchUtils.mapToString(result).trim());
	} catch (Exception e) {
		if (expectValid) {
			e.printStackTrace();
			fail(e.getMessage());
		}
		return;
	}
   }
 
Example #24
Source File: RsJsonTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * RsJSON can build JSON response.
 * @throws IOException If some problem inside
 */
@Test
public void buildsJsonResponse() throws IOException {
    final String key = "name";
    final JsonStructure json = Json.createObjectBuilder()
        .add(key, "Jeffrey Lebowski")
        .build();
    MatcherAssert.assertThat(
        Json.createReader(
            new RsJson(json).body()
        ).readObject().getString(key),
        Matchers.startsWith("Jeffrey")
    );
}
 
Example #25
Source File: TargetDirectoryJsonStructureWriter.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void writeJsonStructure(Module<NType, NClass> module,
		JsonStructure schema, String fileName) {
	try {
		writeStructure(targetDirectory, "", fileName, schema);
	} catch (IOException ioex) {
		errorReceiver.error(new SAXParseException(MessageFormat.format(
				"Could not create the code for the module [{0}].",
				module.getName()), null, ioex));
	}
}
 
Example #26
Source File: JsonValueResolverTest.java    From trimou with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnwrapJsonArrayElementAtIndex()
        throws FileNotFoundException {
    // https://github.com/trimou/trimou/issues/26
    String json = "{\"users\": [\"izeye\", \"always19\"]}";
    String template = "One of users is {{users.0}}.";
    JsonStructure jsonStructure = Json.createReader(new StringReader(json))
            .read();
    MustacheEngine engine = getEngine();
    Mustache mustache = engine.compileMustache("unwrap_array_index",
            template);
    assertEquals("One of users is izeye.", mustache.render(jsonStructure));
}
 
Example #27
Source File: RsJson.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param json JSON object
 * @throws IOException If fails
 */
public RsJson(final JsonStructure json) throws IOException {
    this(
        new RsJson.Source() {
            @Override
            public JsonStructure toJson() {
                return json;
            }
        }
    );
}
 
Example #28
Source File: TestClass7.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
@javax.ws.rs.GET
public JsonStructure method() {
    if ("".equals(""))
        return Json.createArrayBuilder().add(true).add("duke").build();

    return Json.createObjectBuilder().add("key", "value").build();
}
 
Example #29
Source File: TestClass38.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
@javax.ws.rs.GET
public Response method() {
    JsonStructure structure = Json.createArrayBuilder().add("duke").add(42).build();
    if ("".equals(""))
        structure = Json.createObjectBuilder().add("duke", 42).add("key", "value").build();
    return Response.ok(structure).build();
}
 
Example #30
Source File: SystemInputJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the JSON object that represents the given function input definition.
 */
private static JsonStructure toJson( FunctionInputDef functionInput)
  {
  JsonObjectBuilder builder = Json.createObjectBuilder();

  addAnnotations( builder, functionInput);

  Arrays.stream( functionInput.getVarTypes()).forEach( varType -> builder.add( varType, toJson( functionInput, varType)));

  return builder.build();
  }