Java Code Examples for javax.json.JsonReader#readArray()

The following examples show how to use javax.json.JsonReader#readArray() . 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: JsonpTest.java    From ee8-sandbox with Apache License 2.0 8 votes vote down vote up
@Test
public void testJsonPatch() {
    JsonReader reader = Json.createReader(JsonpTest.class.getResourceAsStream("/persons.json"));
    JsonArray jsonaArray = reader.readArray();

    JsonPatch patch = Json.createPatchBuilder()        
            .replace("/0/name", "Duke Oracle")
            .remove("/1")
            .build();

    JsonArray result = patch.apply(jsonaArray);
    System.out.println(result.toString());
    
    Type type = new ArrayList<Person>() {}.getClass().getGenericSuperclass();

    List<Person> person = JsonbBuilder.create().fromJson(result.toString(), type);
    assertEquals("Duke Oracle", person.get(0).getName());

}
 
Example 2
Source File: JsonDemo.java    From Java-EE-8-and-Angular with MIT License 6 votes vote down vote up
private void jsonStreamFilter() {
    JsonReader reader = Json.createReader(JsonDemo.class.getResourceAsStream("/sample_priority.json"));
    JsonArray jsonarray = reader.readArray();

    JsonArray result = jsonarray.getValuesAs(JsonObject.class)
            .stream()
            .filter(j -> "High".equals(j.getString("priority")))
            .collect(JsonCollectors.toJsonArray());
    System.out.println("Stream Filter: " + result);
}
 
Example 3
Source File: Objects.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a JSON array from a string. 
 * 
 * @param jsonString A string that is to be decoded as a JSON.
 * @return JsonArray if the decoding was successful, or null if something went wrong (string is not a valid JSON etc.).  
 */
public JsonArray readJsonArray(String jsonString) {
	
	if (jsonString == null) {
		return null;
	}
	
	// make a JSON from the incoming String - any string that is not a valid JSON will throw exception
	JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
	
	JsonArray json;
	
	try {
		json = jsonReader.readArray();
	} catch (Exception e) {
		System.out.println("Exception during reading JSON array: " 
					+ e.getMessage());
		
		return null;
	} finally {
		jsonReader.close();
	}
	
	return json;
}
 
Example 4
Source File: MavenDependencySettingsService.java    From sonarqube-licensecheck with Apache License 2.0 6 votes vote down vote up
public void deleteMavenDependency(final String key)
{
    List<MavenDependency> newDependencyList = new ArrayList<>();
    JsonReader jsonReader =
        Json.createReader(new StringReader(persistentSettings.getSettings().getString(ALLOWED_DEPENDENCIES_KEY)));
    JsonArray jsonArray = jsonReader.readArray();
    jsonReader.close();

    for (int i = 0; i < jsonArray.size(); i++)
    {
        JsonObject jsonObject = jsonArray.getJsonObject(i);
        if (!jsonObject.getString("nameMatches").equals(key))
        {
            newDependencyList
                .add(new MavenDependency(jsonObject.getString("nameMatches"), jsonObject.getString("license")));
        }
    }
    saveSettings(newDependencyList);
}
 
Example 5
Source File: MavenDependencyService.java    From sonarqube-licensecheck with Apache License 2.0 6 votes vote down vote up
public List<MavenDependency> getMavenDependencies()
{
    final List<MavenDependency> mavenDependencies = new ArrayList<>();
    String dependencyString = configuration.get(ALLOWED_DEPENDENCIES_KEY).orElse("[]");

    JsonReader jsonReader = Json.createReader(new StringReader(dependencyString));
    JsonArray jsonArray = jsonReader.readArray();
    jsonReader.close();

    for (int i = 0; i < jsonArray.size(); i++)
    {
        JsonObject jsonObject = jsonArray.getJsonObject(i);
        mavenDependencies
            .add(new MavenDependency(jsonObject.getString("nameMatches"), jsonObject.getString("license")));
    }
    return mavenDependencies;
}
 
Example 6
Source File: JsonpTest.java    From ee8-sandbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonPointer() {
    JsonReader reader = Json.createReader(JsonpTest.class.getResourceAsStream("/persons.json"));

    JsonArray arrays = reader.readArray();

    JsonPointer p = Json.createPointer("/0/name");
    JsonValue name = p.getValue(arrays);

    System.out.println("json value ::" + name);

   // assertEquals("Duke", name.toString());

    JsonReader objReader = Json.createReader(JsonpTest.class.getResourceAsStream("/person.json"));
    JsonPointer p2 = Json.createPointer("/name");
    JsonValue name2 = p2.getValue(objReader.readObject());
    System.out.println("json value ::" + name2);
  //  assertEquals("Duke", name2.toString());
}
 
Example 7
Source File: DataTablesPagingHelper.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Extract the sorting information from the DataTablesInputs into a more generic form.
 *
 * @param form object containing the view's data
 * @param view posted view containing the collection
 * @param dataTablesInputs the parsed request data from dataTables
 * @return the List of ColumnSort elements representing the requested sort columns, types, and directions
 */
private static List<ColumnSort> buildColumnSorts(View view, ViewModel form, DataTablesInputs dataTablesInputs,
        CollectionGroup collectionGroup) {
    int[] sortCols = dataTablesInputs.iSortCol_; // cols being sorted on (for multi-col sort)
    boolean[] sortable = dataTablesInputs.bSortable_; // which columns are sortable
    String[] sortDir = dataTablesInputs.sSortDir_; // direction to sort

    // parse table options to gather the sort types
    String aoColumnDefsValue = (String) form.getViewPostMetadata().getComponentPostData(collectionGroup.getId(),
            UifConstants.TableToolsKeys.AO_COLUMN_DEFS);

    JsonArray jsonColumnDefs = null;
    if (!StringUtils.isEmpty(aoColumnDefsValue)) { // we'll parse this using a JSON library to make things simpler
        // function definitions are not allowed in JSON
        aoColumnDefsValue = aoColumnDefsValue.replaceAll("function\\([^)]*\\)\\s*\\{[^}]*\\}", "\"REDACTED\"");
        JsonReader jsonReader = Json.createReader(new StringReader(aoColumnDefsValue));
        jsonColumnDefs = jsonReader.readArray();
    }

    List<ColumnSort> columnSorts = new ArrayList<ColumnSort>(sortCols.length);

    for (int sortColsIndex = 0; sortColsIndex < sortCols.length; sortColsIndex++) {
        int sortCol = sortCols[sortColsIndex]; // get the index of the column being sorted on

        if (sortable[sortCol]) {
            String sortType = getSortType(jsonColumnDefs, sortCol);
            ColumnSort.Direction sortDirection = ColumnSort.Direction.valueOf(sortDir[sortColsIndex].toUpperCase());
            columnSorts.add(new ColumnSort(sortCol, sortDirection, sortType));
        }
    }

    return columnSorts;
}
 
Example 8
Source File: Util.java    From maximorestclient with Apache License 2.0 5 votes vote down vote up
public static JsonArray readFile2JsonArray(String filePath) throws FileNotFoundException{
	File file = new File(filePath);
    FileInputStream fis = new FileInputStream(file);
	JsonReader rdr = Json.createReader(fis);
	JsonArray jar = rdr.readArray();
	return jar;
}
 
Example 9
Source File: AdminServlet.java    From sample.microservices.12factorapp with Apache License 2.0 5 votes vote down vote up
private String parse(String stats) throws IOException {
    // Convert string to jsonObject
    InputStream is = new ByteArrayInputStream(stats.getBytes("UTF-8"));
    JsonReader reader = Json.createReader(is);
    String output = "";
    try {
        JsonArray jsonArray = reader.readArray();
        JsonObject jsonObject = jsonArray.getJsonObject(0);
        JsonObject topLevelValue = (JsonObject) jsonObject.get("value");
        JsonObject value = (JsonObject) topLevelValue.get("value");
        JsonValue currentValue = value.get("currentValue");
        JsonValue desc = value.get("description");
        output = "Stats:" + desc.toString() + ": " + currentValue.toString();
    } catch (JsonException e) {
        reader.close();
        is.close();
        if (e.getMessage().equals("Cannot read JSON array, found JSON object")) {
            output = "MXBean not created yet, the application must be accessed at least "
                     + "once to get statistics";
        } else {
            output = "A JSON Exception occurred: " + e.getMessage();
        }
    }
    reader.close();
    is.close();
    return output;
}
 
Example 10
Source File: UdgerPerformanceTest.java    From udger-java with MIT License 5 votes vote down vote up
public static void main(String args[]) {
    InputStream is = UdgerUaTest.class.getResourceAsStream("test_ua.json");
    JsonReader jsonReader = javax.json.Json.createReader(is);
    jsonArray = jsonReader.readArray();
    UdgerParser.ParserDbData parserDbData = new UdgerParser.ParserDbData("udgerdb_v3.dat");
    for (int i=0; i<10; i++) {
        System.out.println("### Test : " + (i+1));
        testSerial(parserDbData);
    }
}
 
Example 11
Source File: StoredProcedureTest.java    From aceql-http with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void parseJson() throws Exception {

/*

	"parameters_out_per_name":[
           {
               "out_param_two":"13"
           },
           {
               "out_param_three":"12"
           }
   	],
 */

String jsonContent = 
"[{\"out_param_two\":\"13\"}, {\"out_param_three\":\"12\"}]";

       JsonReader reader = Json.createReader(new StringReader(jsonContent));
       JsonArray jsonArray = reader.readArray();

for (JsonValue jsonValue : jsonArray) {
    System.out.println(jsonValue.toString());
    JsonObject jsonObject = (JsonObject)jsonValue;
    System.out.println(jsonObject.keySet());;
}
    
   }
 
Example 12
Source File: SpringCloudRelease.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
@Override
@Cacheable("springCloudVersions")
public Collection<String> getSpringCloudVersions() throws IOException {
	List<String> releaseVersions = new ArrayList<>();
	JsonReader reader = github.entry().uri().path(SPRING_CLOUD_RELEASE_TAGS_PATH)
			.back().fetch().as(JsonResponse.class).json();
	JsonArray tags = reader.readArray();
	reader.close();
	List<JsonObject> tagsList = tags.getValuesAs(JsonObject.class);
	for (JsonObject obj : tagsList) {
		releaseVersions.add(obj.getString("name").replaceFirst("v", ""));
	}
	return releaseVersions;
}
 
Example 13
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private RobotType[] getAllTypes(SpanContext parent) {
	List<RobotType> types = new ArrayList<RobotType>();
	String result = doGeneralGetCall(urlFactory + "/robottypes", parent, References.CHILD_OF);
	JsonReader reader = Json.createReader(new StringReader(result));
	JsonArray array = reader.readArray();
	for (JsonValue jsonValue : array) {
		types.add(RobotType.fromJSon(jsonValue.asJsonObject()));
	}
	return types.toArray(new RobotType[0]);
}
 
Example 14
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Color[] getAllColors(SpanContext parent) {
	List<Color> paints = new ArrayList<Color>();
	String result = doGeneralGetCall(urlFactory + "/paints", parent, References.CHILD_OF);
	JsonReader reader = Json.createReader(new StringReader(result));
	JsonArray array = reader.readArray();
	for (JsonValue jsonValue : array) {
		paints.add(Color.fromString(jsonValue.asJsonObject().getString(Robot.KEY_COLOR)));
	}
	return paints.toArray(new Color[0]);
}
 
Example 15
Source File: JsonDemo.java    From Java-EE-8-and-Angular with MIT License 5 votes vote down vote up
private void jsonStreamGroup() {
    JsonReader reader = Json.createReader(JsonDemo.class.getResourceAsStream("/sample_priority.json"));
    JsonArray jsonarray = reader.readArray();

    JsonObject result = jsonarray.getValuesAs(JsonObject.class)
            .stream()
            .collect(JsonCollectors.groupingBy(
                    x -> ((JsonObject) x).getJsonString("priority")
                            .getString()
            ));
    System.out.println("Stream Group: " + result);

}
 
Example 16
Source File: JsonUtil.java    From hadoop-etl-udfs with MIT License 4 votes vote down vote up
public static JsonArray getJsonArray(String data) throws Exception {
    JsonReader jr = Json.createReader(new StringReader(data));
    JsonArray arr = jr.readArray();
    jr.close();
    return arr;
}
 
Example 17
Source File: Counters.java    From vicinity-gateway-api with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Load messages from counters file
 */
public ArrayList<JsonObject> loadCounters() {
	// loaded data
	JsonArray raw;
	ArrayList<JsonObject> data = new ArrayList<JsonObject>();
			
	String objectDataFileName = String.format(countersFile, COUNTERS_PERSISTENCE_FILE);
	File file = new File(objectDataFileName);
	// if file exist then try to open file and load data
       if(file.exists()) {
   		try {
   			
       		InputStream is = new FileInputStream(file);
               String jsonTxt = IOUtils.toString(is, "UTF-8");
               is.close();
               
               JsonReader jsonReader = Json.createReader(new StringReader(jsonTxt));
               
               try {
               	raw = jsonReader.readArray();
       		} catch (Exception e) {
       			
       			logger.severe("PersistanceManager#loadThingDescriptionFromFile: Exception during reading JSON object: " 
       						+ e.getMessage());
       			
       			return null;
       		} finally {
       			jsonReader.close();
       		}
               
   			logger.fine("Counters were loaded from file - " + file.getName() );
   			
   	    } catch (IOException i) {
   	    	
   	    	logger.warning("Counters could not be loaded from file - " + file.getName() );
   	    	i.printStackTrace();
   	        return null;
   	        
   	    } 
   		

   		// Convert to ArrayList 
		if (raw != null) { 
		   for (int i=0;i< raw.size();i++){ 
		    data.add(raw.getJsonObject(i));
		   } 
		} 

       	return data;
       }
	
       logger.info("There are no persisted counters, starting new list...");
	return data;
}
 
Example 18
Source File: JsonReporterTest.java    From revapi with Apache License 2.0 4 votes vote down vote up
@Test
public void testReportsWritten() throws Exception {
    JsonReporter reporter = new JsonReporter();

    Revapi r = new Revapi(PipelineConfiguration.builder().withReporters(JsonReporter.class).build());

    AnalysisContext ctx = AnalysisContext.builder(r)
            .withOldAPI(API.of(new FileArchive(new File("old-dummy.archive"))).build())
            .withNewAPI(API.of(new FileArchive(new File("new-dummy.archive"))).build())
            .build();

    AnalysisContext reporterCtx = r.prepareAnalysis(ctx).getFirstConfigurationOrNull(JsonReporter.class);

    reporter.initialize(reporterCtx);

    buildReports().forEach(reporter::report);

    StringWriter out = new StringWriter();
    PrintWriter wrt = new PrintWriter(out);

    reporter.setOutput(wrt);

    reporter.close();

    JsonReader reader = Json.createReader(new StringReader(out.toString()));
    JsonArray diffs = reader.readArray();

    assertEquals(2, diffs.size());
    JsonObject diff = diffs.getJsonObject(0);
    assertEquals("code1", diff.getString("code"));
    assertEquals("old1", diff.getString("old"));
    assertEquals("new1", diff.getString("new"));
    JsonArray classifications = diff.getJsonArray("classification");
    assertEquals(1, classifications.size());
    JsonObject classification = classifications.getJsonObject(0);
    assertEquals("SOURCE", classification.getString("compatibility"));
    assertEquals("BREAKING", classification.getString("severity"));
    JsonArray attachments = diff.getJsonArray("attachments");
    JsonObject attachment = attachments.getJsonObject(0);
    assertEquals("at1", attachment.getString("name"));
    assertEquals("at1val", attachment.getString("value"));

    diff = diffs.getJsonObject(1);
    assertEquals("code2", diff.getString("code"));
    assertEquals("old2", diff.getString("old"));
    assertEquals("new2", diff.getString("new"));
    classifications = diff.getJsonArray("classification");
    assertEquals(1, classifications.size());
    classification = classifications.getJsonObject(0);
    assertEquals("BINARY", classification.getString("compatibility"));
    assertEquals("BREAKING", classification.getString("severity"));
    attachments = diff.getJsonArray("attachments");
    attachment = attachments.getJsonObject(0);
    assertEquals("at2", attachment.getString("name"));
    assertEquals("at2val", attachment.getString("value"));
}