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

The following examples show how to use javax.json.JsonReader#close() . 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: AuthResource.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
private String getSigningKeys(String url) {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();
    JsonReader jsonReader = null;

    try {
        com.squareup.okhttp.Response response = client.newCall(request).execute();
        jsonReader = Json.createReader(new StringReader(response.body().string()));
        JsonObject object = jsonReader.readObject();
        JsonArray keys = object.getJsonArray("keys");
        return keys.toString();
    } catch (IOException | JsonParsingException e) {
        LOGGER.log(Level.SEVERE, null, e);
        return null;
    } finally {
        if (jsonReader != null) {
            jsonReader.close();
        }
    }
}
 
Example 2
Source File: clientUtil.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static String keyHandleDecode(String Input, int returnType) {

        JsonReader jsonReader = Json.createReader(new StringReader(Input));
        JsonObject jsonObject = jsonReader.readObject();
        jsonReader.close();
        //System.out.println("Last name : "+jsonObject.getString("swair"));
        if (returnType == 0) {
            return jsonObject.getString("key");

        } else if (returnType == 1) {

            return jsonObject.getString("sha1");

        } else {
            return jsonObject.getString("origin_hash");
        }

    }
 
Example 3
Source File: clientUtilAuth.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
public String decodePreauth(String input, int returntype) {

        JsonReader jsonReader = Json.createReader(new StringReader(input));
        JsonObject jsonObject = jsonReader.readObject();
        jsonReader.close();

        if (returntype == 0) {
            return jsonObject.getString(CSConstants.JSON_USER_KEY_HANDLE);
        } else if (returntype == 1) {
            return jsonObject.getString(CSConstants.JSON_KEY_SESSIONID);
        } else if (returntype == 2) {
            return jsonObject.getString(CSConstants.JSON_KEY_CHALLENGE);
        } else if (returntype == 3) {
            return jsonObject.getString(CSConstants.JSON_KEY_VERSION);
        } else {
            return jsonObject.getString(CSConstants.JSON_KEY_APP_ID);
        }

    }
 
Example 4
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 5
Source File: CommunicationManager.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a JSON object from a string. 
 * 
 * @param jsonString A string that is to be decoded as a JSON.
 * @return JsonObject if the decoding was successful, or null if something went wrong (string is not a valid JSON etc.).  
 */
public JsonObject readJsonObject(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));
	
	JsonObject json;
	
	try {
		json = jsonReader.readObject();
	} catch (Exception e) {
		logger.severe("Exception during reading JSON object: " 
					+ e.getMessage());
		
		return null;
	} finally {
		jsonReader.close();
	}
	
	return json;
}
 
Example 6
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 7
Source File: JsonProvider.java    From rapid with MIT License 5 votes vote down vote up
@Override
public Object readFrom(Class type, Type genericType, Annotation[] annotations,
                       MediaType mediaType, MultivaluedMap httpHeaders,
                       InputStream entityStream) throws IOException, WebApplicationException {
    // from HTML to methods having @Consumes
    JsonReader jsonReader = Json.createReader(entityStream);
    JsonStructure object = jsonReader.read();
    jsonReader.close();
    entityStream.close();
    return object;
}
 
Example 8
Source File: UserDefinedMetrics.java    From mysql_perf_analyzer with Apache License 2.0 5 votes vote down vote up
public static UserDefinedMetrics createFromJson(java.io.InputStream in)
{
	JsonReader jsonReader = null;
	UserDefinedMetrics udm = null;
	try
	{
		jsonReader = javax.json.Json.createReader(in);
		JsonObject jsonObject = jsonReader.readObject();
		jsonReader.close();
		udm = new UserDefinedMetrics(jsonObject.getString("groupName"));
		udm.setAuto("y".equalsIgnoreCase(jsonObject.getString("auto", null)));
		udm.setStoreInCommonTable("y".equalsIgnoreCase(jsonObject.getString("storeInCommonTable", null)));
		udm.setSource(jsonObject.getString("source"));
		udm.setUdmType(jsonObject.getString("type"));
		udm.setNameCol(jsonObject.getString("nameColumn", null));
		udm.setValueCol(jsonObject.getString("valueColumn", null));
		udm.setKeyCol(jsonObject.getString("keyColumn", null));
		udm.setSql(jsonObject.getString("sql", null));
		
		JsonArray metrics = jsonObject.getJsonArray("metrics");
		if(metrics != null )
		{
			int mlen = metrics.size();
			for(int i=0; i<mlen; i++)
			{
				JsonObject mobj = metrics.getJsonObject(i);
				udm.addmetric(mobj.getString("name"), 
						mobj.getString("sourceName"), 
						"y".equalsIgnoreCase(mobj.getString("inc")),
						Metric.strToMetricDataType(mobj.getString("dataType")));
			}
		}
	}catch(Exception ex)
	{
		logger.log(Level.WARNING, "Error to parse UDM", ex);
		//TODO
	}
	return udm;
}
 
Example 9
Source File: MonaJsonParser.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run() {
  error = 0;
  correct = 0;
  for (String l : lines) {
    if (l == null || l.isEmpty())
      continue;

    if (isStopped || (mainTask != null && mainTask.isCanceled())) {
      isDone = true;
      return;
    }
    JsonReader reader = null;
    try {
      reader = Json.createReader(new StringReader(l));
      JsonObject json = reader.readObject();
      SpectralDBEntry entry = getDBEntry(json);
      if (entry != null) {
        addLibraryEntry(entry);
        correct++;
      } else
        error++;
    } catch (Exception ex) {
      error++;
      logger.log(Level.WARNING, "Error for entry", ex);
    } finally {
      if (reader != null)
        reader.close();
    }
  }
  isDone = true;
}
 
Example 10
Source File: EventSampler.java    From BotServiceStressToolkit with MIT License 5 votes vote down vote up
private JsonObject getChanneldata() {
	String jsonStr = getPropertyAsString(CHANNELDATA);
	System.out.println("JSON string: " + jsonStr);
	JsonReader jsonReader = Json.createReader(new StringReader(jsonStr));
	JsonObject obj = jsonReader.readObject();
	jsonReader.close();
	
	return obj;
}
 
Example 11
Source File: ExampleResource.java    From example-health-jee-openshift with Apache License 2.0 5 votes vote down vote up
@POST
  @Path("/v1/login/user")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public Response login(String body) {
      // {"UID":username,"PASS":password}
       Jsonb jsonb = JsonbBuilder.create();
       Credentials c = jsonb.fromJson(body, Credentials.class);
      List<Patient> results = entityManager.createNamedQuery("Patient.login", Patient.class)
              .setParameter("userId", c.UID)
              .setParameter("password", c.PASS)
              .getResultList();
      logger.info("Found this many patients: " + results.size());
      int returnCode = 0;
      if (results.size() == 0) {
          returnCode=1;
      }

      /*
          "ResultSet Output": [
          {
              "PATIENTID": 1
          }
          ],
      "StatusCode": 200,
      "StatusDescription": "Execution Successful"
  }*/
      if (returnCode==1) {
          return Response.status(Status.NOT_FOUND).build();
      }
      
      String loginBlob = "{\"ResultSet Output\":" + jsonb.toJson(results) 
      + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}";

      logger.info("login blob: " + loginBlob);
      JsonReader jsonReader = Json.createReader(new StringReader(loginBlob));
      JsonObject jresponse  = jsonReader.readObject();
      jsonReader.close();
return Response.ok(jresponse).build();         
  }
 
Example 12
Source File: Message.java    From sample-room-java with Apache License 2.0 5 votes vote down vote up
public JsonObject getParsedBody() {
    JsonReader jsonReader = Json.createReader(new StringReader(payload));
    JsonObject object = jsonReader.readObject();
    jsonReader.close();

    return object;
}
 
Example 13
Source File: ExampleResource.java    From example-health-jee-openshift with Apache License 2.0 5 votes vote down vote up
@GET
   @Path("/v1/getInfo/patients/{patId}")
   @Produces(MediaType.APPLICATION_JSON)
   public Response getPatient(@PathParam("patId") String patId) {
       List<Patient> results = entityManager.createNamedQuery("Patient.findPatient", Patient.class)
               .setParameter("pid", patId)
               .getResultList();
       Jsonb jsonb = JsonbBuilder.create();
       logger.info("Found this many patients with id " + patId + " = " + results.size());
       int returnCode = 0;
       if (results.size() == 0) {
           returnCode=1;
           // return Response.ok("No patients found.").build();
       }

       String patientBlob = "{\"HCCMAREA\": {" + 
       " \"CA_REQUEST_ID\" : \"01IPAT\"," + 
       " \"CA_RETURN_CODE\": " + returnCode + "," + 
       " \"CA_PATIENT_ID\": \"" + patId + "\"," + 
       " \"CA_PATIENT_REQUEST\": " + (returnCode==0 ? jsonb.toJson(results.get(0)) : "\"\"") +
       "}}";

       logger.info("Patient blob: " + patientBlob);

       JsonReader jsonReader = Json.createReader(new StringReader(patientBlob));
           
       JsonObject jresponse  = jsonReader.readObject();
       jsonReader.close();
	return Response.ok(jresponse).build();
}
 
Example 14
Source File: ExampleResource.java    From example-health-jee-openshift with Apache License 2.0 5 votes vote down vote up
@GET
  @Path("/v1/getInfo/patients")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getPatients() {
      List<Patient> results = entityManager.createNamedQuery("Patient.getPatients", Patient.class).getResultList();
      Jsonb jsonb = JsonbBuilder.create();
      String patientBlob = "{\"ResultSet Output\": " + jsonb.toJson(results)
      + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}";
      
      JsonReader jsonReader = Json.createReader(new StringReader(patientBlob));
          
      JsonObject jresponse  = jsonReader.readObject();
      jsonReader.close();
return Response.ok(jresponse).build();
  }
 
Example 15
Source File: ExampleResource.java    From example-health-jee-openshift with Apache License 2.0 5 votes vote down vote up
@GET
   @Path("/v1/showAllergies")
   @Produces(MediaType.APPLICATION_JSON)
   public Response showAllergies() {
       /*
       "ResultSet Output": [
           {
               "CITY": "Albany              ",
               "POSTCODE": "12202     ",
               "PATIENT_NUM": 1437,
               "BIRTHDATE": "1961-11-26",
               "ALLERGY_START": "1991-10-08",
               "ALLERGY_STOP": null,
               "DESCRIPTION": "Allergy to fish"
           } ],
       "StatusCode": 200,
       "StatusDescription": "Execution Successful"
   }     
   */   


   // select Patients.patient_id, Patients.birthdate, Patients.city, Patients.postcode, Allergies.description, Allergies.allergy_start, Allergies.allergy_stop from Patients JOIN Allergies ON Patients.patient_id = Allergies.patient_id;

       List<AllergyList> results = entityManager.createNamedQuery("Allergy.getAllergies", AllergyList.class).getResultList();

       Jsonb jsonb = JsonbBuilder.create();
       String allergyBlob = "{\"ResultSet Output\": " + jsonb.toJson(results)
       + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}";

       JsonReader jsonReader = Json.createReader(new StringReader(allergyBlob));
           
       JsonObject jresponse  = jsonReader.readObject();
       jsonReader.close();

       return Response.ok(jresponse).build();
}
 
Example 16
Source File: Orchestrator.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
private JsonObject stringToJsonObj(String input) {
  try {
    JsonReader jsonReader = Json.createReader(new StringReader(input));
    JsonObject output = jsonReader.readObject();
    jsonReader.close();
    return output;
  } catch (JsonParsingException e) {
    return null;
  }
}
 
Example 17
Source File: Group.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
public static JsonObject stringToJsonObj(String input) {
  try {
    JsonReader jsonReader = Json.createReader(new StringReader(input));
    JsonObject output = jsonReader.readObject();
    jsonReader.close();
    return output;
  } catch (JsonParsingException e) {
    return null;
  }
}
 
Example 18
Source File: ExampleResource.java    From example-health-jee-openshift with Apache License 2.0 4 votes vote down vote up
@GET
    @Path("/v1/listObs/{patId}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response listObs(@PathParam("patId") String patId) {
        List<Observation> results = entityManager.createNamedQuery("Observation.getObservations", Observation.class)
                .setParameter("pid", patId)
                .getResultList();
        Jsonb jsonb = JsonbBuilder.create();
        logger.info("Found this many observations with id " + patId + " = " + results.size());
        int returnCode = 0;
        if (results.size() == 0) {
            returnCode=1;
        }
     
/* output
        Format of JSON output:

        "ResultSet Output": [
            {
                "PATIENTID": 1,
                "DATEOFOBSERVATION": "2018-05-03",
                "CODE": "11111-0 ",
                "DESCRIPTION": "Tobacco smoking status NHIS",
                "NUMERICVALUE": null,
                "CHARACTERVALUE": "Former smoker",
                "UNITS": null
            }],
        "StatusCode": 200,
        "StatusDescription": "Execution Successful"
*/        
        String observationBlob = "{\"ResultSet Output\": " + jsonb.toJson(results)
        + ", \"StatusCode\": 200, \n \"StatusDescription\": \"Execution Successful\"}";

        logger.info("Observation blob: " + observationBlob);

        JsonReader jsonReader = Json.createReader(new StringReader(observationBlob));
            
        JsonObject jresponse  = jsonReader.readObject();
        jsonReader.close();
		return Response.ok(jresponse).build();
        
    }
 
Example 19
Source File: GnpsJsonParser.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public boolean parse(AbstractTask mainTask, File dataBaseFile) throws IOException {
  logger.info("Parsing GNPS spectral library " + dataBaseFile.getAbsolutePath());

  int correct = 0;
  int error = 0;
  // create db
  try (BufferedReader br = new BufferedReader(new FileReader(dataBaseFile))) {
    for (String l; (l = br.readLine()) != null;) {
      // main task was canceled?
      if (mainTask != null && mainTask.isCanceled()) {
        return false;
      }

      JsonReader reader = null;
      try {
        reader = Json.createReader(new StringReader(l));
        JsonObject json = reader.readObject();
        SpectralDBEntry entry = getDBEntry(json);
        if (entry != null) {
          correct++;
          // add entry and process
          addLibraryEntry(entry);
        } else
          error++;
      } catch (Exception ex) {
        error++;
        logger.log(Level.WARNING, "Error for entry", ex);
      } finally {
        if (reader != null)
          reader.close();
      }
      // to many errors? wrong data format?
      if (error > 5 && correct < 5) {
        logger.log(Level.WARNING, "This file was no GNPS spectral json library");
        return false;
      }
    }
  }
  // finish and process last entries
  finish();

  return true;
}