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

The following examples show how to use javax.json.JsonObject#getInt() . 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: InventoryEndpointIT.java    From boost with Eclipse Public License 1.0 6 votes vote down vote up
public void testHostRegistration() {
    this.visitLocalhost();

    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
    this.assertResponse(baseUrl, response);

    JsonObject obj = response.readEntity(JsonObject.class);

    int expected = 1;
    int actual = obj.getInt("total");
    assertEquals("The inventory should have one entry for localhost", expected, actual);

    boolean localhostExists = obj.getJsonArray("systems").getJsonObject(0).get("hostname").toString()
            .contains("localhost");
    assertTrue("A host was registered, but it was not localhost", localhostExists);

    response.close();
}
 
Example 2
Source File: LoginApp.java    From OrionAlpha with GNU General Public License v3.0 6 votes vote down vote up
private void initializeDB() {
    try (JsonReader reader = Json.createReader(new FileReader("Database.img"))) {
        JsonObject dbData = reader.readObject();
        
        int dbPort = dbData.getInt("dbPort", 3306);
        String dbName = dbData.getString("dbGameWorld", "orionalpha");
        String dbSource = dbData.getString("dbGameWorldSource", "127.0.0.1");
        String[] dbInfo = dbData.getString("dbGameWorldInfo", "root,").split(",");
        
        // Construct the instance of the Database
        Database.createInstance(dbName, dbSource, dbInfo[0], dbInfo.length == 1 ? "" : dbInfo[1], dbPort);
        
        // Load the initial instance of the Database
        Database.getDB().load();
        
        Logger.logReport("DB configuration parsed successfully");
    } catch (FileNotFoundException ex) {
        ex.printStackTrace(System.err);
    }
}
 
Example 3
Source File: ShopApp.java    From OrionAlpha with GNU General Public License v3.0 6 votes vote down vote up
private void initializeDB() {
    try (JsonReader reader = Json.createReader(new FileReader("Database.img"))) {
        JsonObject dbData = reader.readObject();

        int dbPort = dbData.getInt("dbPort", 3306);
        String dbName = dbData.getString("dbGameWorld", "orionalpha");
        String dbSource = dbData.getString("dbGameWorldSource", "127.0.0.1");
        String[] dbInfo = dbData.getString("dbGameWorldInfo", "root,").split(",");

        // Construct the instance of the Database
        Database.createInstance(dbName, dbSource, dbInfo[0], dbInfo.length == 1 ? "" : dbInfo[1], dbPort);

        // Load the initial instance of the Database
        Database.getDB().load();

        Logger.logReport("DB configuration parsed successfully");
    } catch (FileNotFoundException ex) {
        ex.printStackTrace(System.err);
    }
}
 
Example 4
Source File: VehicleDeserializer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Vehicle deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) {
    JsonObject json = parser.getObject();
    String type = json.getString("type");
    switch (type) {
        case "CAR":
            Car car = new Car();
            car.type = type;
            car.seatNumber = json.getInt("seatNumber");
            car.name = json.getString("name");
            return car;
        case "MOTO":
            Moto moto = new Moto();
            moto.type = type;
            moto.name = json.getString("name");
            moto.sideCar = json.getBoolean("sideCar");
            return moto;
        default:
            throw new RuntimeException("Type " + type + "not managed");
    }
}
 
Example 5
Source File: InventoryEndpointIT.java    From boost with Eclipse Public License 1.0 6 votes vote down vote up
public void testHostRegistration() {
    this.visitLocalhost();

    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
    this.assertResponse(baseUrl, response);

    JsonObject obj = response.readEntity(JsonObject.class);

    int expected = 1;
    int actual = obj.getInt("total");
    assertEquals("The inventory should have one entry for localhost", expected, actual);

    boolean localhostExists = obj.getJsonArray("systems").getJsonObject(0).get("hostname").toString()
            .contains("localhost");
    assertTrue("A host was registered, but it was not localhost", localhostExists);

    response.close();
}
 
Example 6
Source File: Utils.java    From KITE with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the integer value from a given json object,
 * overwrite it with System env or a minimum positive value if applicable
 *
 * @param jsonObject           the json object
 * @param key                  name of the attribute
 * @param minimumPositiveValue minimum positive value
 *
 * @return an integer value
 * @throws KiteInsufficientValueException if the value does not exist and no minimum positive value is provided
 */
public static int getIntFromJsonObject(JsonObject jsonObject, String key, int minimumPositiveValue)
  throws KiteInsufficientValueException {
  if (System.getProperty(key) == null) {
    try {
      int value = jsonObject.getInt(key);
      if (value < minimumPositiveValue) {
        return minimumPositiveValue;
      } else {
        return value;
      }
    } catch (NullPointerException e) {
      if (minimumPositiveValue >= 0) {
        return minimumPositiveValue;
      } else {
        throw new KiteInsufficientValueException("Invalid minimum positive value for " + key);
      }
    }
  } else {
    return Integer.parseInt(System.getProperty(key));
  }
}
 
Example 7
Source File: ApiParameters.java    From FHIR with Apache License 2.0 6 votes vote down vote up
public static ApiParameters parse(JsonObject jsonObject) {
    ApiParameters.Builder builder =
            ApiParameters.builder();

    JsonValue t = jsonObject.get("request");
    if (t != null) {
        String request = jsonObject.getString("request");
        builder.request(request);
    }

    t = jsonObject.get("request_status");
    if (t != null) {
        int status = jsonObject.getInt("request_status", -100000000);
        if (status != -100000000) {
            builder.status(status);
        }
    }
    return builder.build();
}
 
Example 8
Source File: StatQueue.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void printStats(String result) {
   printHeadings();

   //should not happen but...
   if (result == null) {
      if (verbose) {
         context.err.println("printStats(): got NULL result string.");
      }
      return;
   }

   JsonObject queuesAsJsonObject = JsonUtil.readJsonObject(result);
   int count = queuesAsJsonObject.getInt("count");
   JsonArray array = queuesAsJsonObject.getJsonArray("data");

   for (int i = 0; i < array.size(); i++) {
      printQueueStats(array.getJsonObject(i));
   }

   if (count > maxRows) {
      context.out.println(String.format("WARNING: the displayed queues are %d/%d, set maxRows to display more queues.", maxRows, count));
   }
}
 
Example 9
Source File: HFCAAffiliation.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
HFCAAffiliationResp(JsonObject result) {
    if (result.containsKey("affiliations")) {
        JsonArray affiliations = result.getJsonArray("affiliations");
        if (affiliations != null && !affiliations.isEmpty()) {
            for (int i = 0; i < affiliations.size(); i++) {
                JsonObject aff = affiliations.getJsonObject(i);
                this.childHFCAAffiliations.add(new HFCAAffiliation(aff));
            }
        }
    }
    if (result.containsKey("identities")) {
        JsonArray ids = result.getJsonArray("identities");
        if (ids != null && !ids.isEmpty()) {
            for (int i = 0; i < ids.size(); i++) {
                JsonObject id = ids.getJsonObject(i);
                HFCAIdentity hfcaID = new HFCAIdentity(id);
                this.identities.add(hfcaID);
            }
        }
    }
    if (result.containsKey("statusCode")) {
        this.statusCode = result.getInt("statusCode");
    }
}
 
Example 10
Source File: SystemTestJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the test case represented by the given JSON object.
 */
private static TestCase asTestCase( JsonObject json)
  {
  TestCase testCase = new TestCase( json.getInt( ID_KEY));
  testCase.setName( json.getString( NAME_KEY, null));

  try
    {
    // Get annotations for this test case.
    Optional.ofNullable( json.getJsonObject( HAS_KEY))
      .ifPresent( has -> has.keySet().stream().forEach( key -> testCase.setAnnotation( key, has.getString( key))));

    // Get test case bindings.
    json.keySet().stream()
      .filter( key -> !(key.equals( ID_KEY) || key.equals( HAS_KEY) || key.equals( NAME_KEY)))
      .forEach( varType -> getVarBindings( varType, json.getJsonObject( varType)).forEach( binding -> testCase.addVarBinding( binding)));

    long failureCount =
      toStream( testCase.getVarBindings())
      .filter( binding -> !binding.isValueValid())
      .count();
    if( failureCount > 1)
      {
      throw new SystemTestException( "Can't have more than one variable bound to a value with failure=true");
      }
    
    return testCase;
    }
  catch( SystemTestException e)
    {
    throw new SystemTestException( String.format( "Error defining test case=%s", testCase.getId()), e);
    }
  }
 
Example 11
Source File: ViewPortfolio.java    From trader with Apache License 2.0 5 votes vote down vote up
private String getTableRows(JsonObject stocks) {
	StringBuffer rows = new StringBuffer();

	if (stocks != null) {
		Iterator<String> keys = stocks.keySet().iterator();

		while (keys.hasNext()) {
			String key = keys.next();
			JsonObject stock = stocks.getJsonObject(key);

			String symbol = stock.getString("symbol");
			int shares = stock.getInt("shares");
			double price = stock.getJsonNumber("price").doubleValue();
			String date = stock.getString("date");
			double total = stock.getJsonNumber("total").doubleValue();
			double commission = stock.getJsonNumber("commission").doubleValue();

			String formattedPrice = "$"+currency.format(price);
			String formattedTotal = "$"+currency.format(total);
			String formattedCommission = "$"+currency.format(commission);

			if (price == ERROR) {
				formattedPrice = ERROR_STRING;
				formattedTotal = ERROR_STRING;
				formattedCommission = ERROR_STRING;
			}

			rows.append("        <tr>");
			rows.append("          <td>"+symbol+"</td>");
			rows.append("          <td>"+shares+"</td>");
			rows.append("          <td>"+formattedPrice+"</td>");
			rows.append("          <td>"+date+"</td>");
			rows.append("          <td>"+formattedTotal+"</td>");
			rows.append("          <td>"+formattedCommission+"</td>");
			rows.append("        </tr>");
		}
	}

	return rows.toString();
}
 
Example 12
Source File: InventoryEndpointIT.java    From boost with Eclipse Public License 1.0 5 votes vote down vote up
public void testEmptyInventory() {
    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
    this.assertResponse(baseUrl, response);

    JsonObject obj = response.readEntity(JsonObject.class);

    int expected = 0;
    int actual = obj.getInt("total");
    assertEquals("The inventory should be empty on application start but it wasn't", expected, actual);

    response.close();
}
 
Example 13
Source File: Client.java    From KITE with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new KiteConfigObject with the given remote address and JsonObject.
 *
 * @param jsonObject JsonObject
 */
public Client(JsonObject jsonObject) {
  this.browserSpecs = new BrowserSpecs(jsonObject);
  this.jsonConfig = jsonObject;
  this.exclude = jsonObject.getBoolean("exclude", false);
  this.capability = new Capability(jsonObject);
  this.name = jsonObject.getString("name", null);
  this.count = jsonObject.getInt("count", 5);
  if (jsonObject.containsKey("app")) {
    this.app = new App(jsonObject.getJsonObject("app"));
  }
  this.kind = this.app != null ? "app" : "browser";
}
 
Example 14
Source File: RegistrationsResource.java    From javaee-bce-pom with Apache License 2.0 5 votes vote down vote up
@POST
public Response register(Registration request, @Context UriInfo info) {
    JsonObject registration = registrations.register(request);
    long id = registration.getInt(Registrations.CONFIRMATION_ID);
    URI uri = info.getAbsolutePathBuilder().path("/" + id).build();
    return Response.created(uri).entity(registration).build();
}
 
Example 15
Source File: WeiboUser.java    From albert with MIT License 5 votes vote down vote up
private void init(JsonObject json) throws WeiboException {
	if (json != null) {
		try {
			id = json.getJsonNumber("id").longValue();
			screenName = json.getString("screen_name");
			name = json.getString("name");
			province = Integer.parseInt(json.getString("province"));
			city = Integer.parseInt(json.getString("city"));
			location = json.getString("location");
			description = WeiboResponseUtil.withNonBmpStripped(json.getString("description"));
			url = json.getString("url");
			profileImageUrl = json.getString("profile_image_url");
			domain = json.getString("domain");
			gender = json.getString("gender");
			followersCount = json.getInt("followers_count");
			friendsCount = json.getInt("friends_count");
			favouritesCount = json.getInt("favourites_count");
			statusesCount = json.getInt("statuses_count");
			createdAt = WeiboResponseUtil.parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
			following = json.getBoolean("following");
			verified = json.getBoolean("verified");
			verifiedType = json.getInt("verified_type");
			verifiedReason = json.getString("verified_reason");
			allowAllActMsg = json.getBoolean("allow_all_act_msg");
			allowAllComment = json.getBoolean("allow_all_comment");
			followMe = json.getBoolean("follow_me");
			avatarLarge = json.getString("avatar_large");
			onlineStatus = json.getInt("online_status");
			biFollowersCount = json.getInt("bi_followers_count");
			if (!json.getString("remark").isEmpty()) {
				remark = json.getString("remark");
			}
			lang = json.getString("lang");
			weihao = json.getString("weihao");
		} catch (JsonException jsone) {
			throw new WeiboException(jsone.getMessage() + ":" + json.toString(), jsone);
		}
	}
}
 
Example 16
Source File: LoginApp.java    From OrionAlpha with GNU General Public License v3.0 5 votes vote down vote up
private void initializeCenter() {
    try (JsonReader reader = Json.createReader(new FileReader("Login.img"))) {
        JsonObject loginData = reader.readObject();
        
        this.port = loginData.getInt("port", 8484);
        this.centerPort = loginData.getInt("centerPort", 8383);
        this.addr = loginData.getString("PublicIP", "127.0.0.1");
        
        Logger.logReport("Login configuration parsed successfully");
    } catch (FileNotFoundException ex) {
        ex.printStackTrace(System.err);
    }
}
 
Example 17
Source File: LibertyRestEndpoint.java    From microservices-traffic-management-using-istio with Apache License 2.0 4 votes vote down vote up
private JsonObject getRatings(Cookie user, String xreq, String xtraceid, String xspanid,
                              String xparentspanid, String xsampled, String xflags, String xotspan){
  ClientBuilder cb = ClientBuilder.newBuilder();
  String timeout = star_color.equals("black") ? "10000" : "2500";
  cb.property("com.ibm.ws.jaxrs.client.connection.timeout", timeout);
  cb.property("com.ibm.ws.jaxrs.client.receive.timeout", timeout);
  Client client = cb.build();
  WebTarget ratingsTarget = client.target(ratings_service);
  Invocation.Builder builder = ratingsTarget.request(MediaType.APPLICATION_JSON);
  if(xreq!=null) {
    builder.header("x-request-id",xreq);
  }
  if(xtraceid!=null) {
    builder.header("x-b3-traceid",xtraceid);
  }
  if(xspanid!=null) {
    builder.header("x-b3-spanid",xspanid);
  }
  if(xparentspanid!=null) {
    builder.header("x-b3-parentspanid",xparentspanid);
  }
  if(xsampled!=null) {
    builder.header("x-b3-sampled",xsampled);
  }
  if(xflags!=null) {
    builder.header("x-b3-flags",xflags);
  }
  if(xotspan!=null) {
    builder.header("x-ot-span-context",xotspan);
  }
  if(user!=null) {
    builder.cookie(user);
  }
  Response r = builder.get();
  int statusCode = r.getStatusInfo().getStatusCode();
  if (statusCode == Response.Status.OK.getStatusCode() ) {
    StringReader stringReader = new StringReader(r.readEntity(String.class));
    try (JsonReader jsonReader = Json.createReader(stringReader)) {
       JsonObject j = jsonReader.readObject();
       JsonObjectBuilder jb = Json.createObjectBuilder();
       for(String key : j.keySet()){
         int count = j.getInt(key);
         String stars = "<font color=\""+ star_color +"\">";
         for(int i=0; i<count; i++){
           stars += "<span class=\"glyphicon glyphicon-star\"></span>";
         }
         stars += "</font>";
         if(count<5){
           for(int i=0; i<(5-count); i++){
             stars += "<span class=\"glyphicon glyphicon-star-empty\"></span>";
           }
         }
         jb.add(key,stars);
       }
       JsonObject result = jb.build();
       return result;
    }
  }else{
    System.out.println("Error: unable to contact "+ratings_service+" got status of "+statusCode);
    return null;
  }
}
 
Example 18
Source File: NetworkMessageResponse.java    From vicinity-gateway-api with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Takes the JSON object that came over the network 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_REQUESTID) ||
			!json.containsKey(ATTR_SOURCEOID) ||
			!json.containsKey(ATTR_DESTINATIONOID) ||
			!json.containsKey(ATTR_ERROR) ||
			!json.containsKey(ATTR_RESPONSECODE) ||
			!json.containsKey(ATTR_RESPONSECODEREASON) ||
			!json.containsKey(ATTR_RESPONSEBODY) ||
			!json.containsKey(ATTR_RESPONSEBODYSUPPLEMENT)) {
		
		return false;
	}
	
	// load values from JSON
	try {
		
		messageType = json.getInt(NetworkMessage.ATTR_MESSAGETYPE);
		requestId = json.getInt(NetworkMessage.ATTR_REQUESTID);
		error = json.getBoolean(ATTR_ERROR);
		responseCode = json.getInt(ATTR_RESPONSECODE);
		
		// null values are special cases in JSON, they get transported as "null" string...
		if (!json.isNull(ATTR_RESPONSECODEREASON)) {
			responseCodeReason = json.getString(ATTR_RESPONSECODEREASON);
		}
		
		if (!json.isNull(ATTR_SOURCEOID)) {
			sourceOid = json.getString(ATTR_SOURCEOID);
		}
		
		if (!json.isNull(ATTR_DESTINATIONOID)) {
			destinationOid = json.getString(ATTR_DESTINATIONOID);
		}
		
		if (!json.isNull(ATTR_CONTENTTYPE)) {
			contentType = json.getString(ATTR_CONTENTTYPE);
		}
		
		if (!json.isNull(ATTR_RESPONSEBODY)) {
			responseBody = json.getString(ATTR_RESPONSEBODY);
		}
		
		if (!json.isNull(ATTR_RESPONSEBODYSUPPLEMENT)) {
			responseBodySupplement = json.getString(ATTR_RESPONSEBODYSUPPLEMENT);
		}
		
	} catch (Exception e) {
		logger.severe("NetworkMessageResponse: Exception while parsing NetworkMessageResponse: " + e.getMessage());
		
		return false;
	}
	
	// process non primitives
	sourceOid = removeQuotes(sourceOid);
	destinationOid = removeQuotes(destinationOid);
	responseCodeReason = removeQuotes(responseCodeReason);
	contentType = removeQuotes(contentType);
	responseBody = removeQuotes(responseBody);
	responseBodySupplement = removeQuotes(responseBodySupplement);
	
	return true;
}
 
Example 19
Source File: CenterSocket.java    From OrionAlpha with GNU General Public License v3.0 4 votes vote down vote up
public void init(JsonObject data) {
    this.addr = data.getString("ip", "127.0.0.1");
    this.port = data.getInt("port", 8383);
    this.worldName = data.getString("worldName", "OrionAlpha");
}
 
Example 20
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;
}