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

The following examples show how to use javax.json.JsonObject#getBoolean() . 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: ObjectHandler.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Called by Gluon CloudLink when an existing object is updated. This implementation will update the Settings object
 * in the database.
 *
 * @param objectIdentifier the identifier of the object that is updated
 * @param payload the raw JSON payload of the object that is updated
 * @return an empty response, as the response is ignored by Gluon CloudLink
 */
@POST
@Path("/update")
@Consumes(MediaType.APPLICATION_JSON + "; " + CHARSET)
@Produces(MediaType.APPLICATION_JSON + "; " + CHARSET)
public String updateObject(@PathParam("objectIdentifier") String objectIdentifier,
                           String payload) {
    LOG.log(Level.INFO, "Updated object with id " + objectIdentifier + ": " + payload);
    try (JsonReader jsonReader = Json.createReader(new StringReader(payload))) {
        JsonObject jsonObject = jsonReader.readObject();
        boolean showDate = !jsonObject.containsKey("showDate") || jsonObject.getBoolean("showDate");
        boolean ascending = !jsonObject.containsKey("ascending") || jsonObject.getBoolean("ascending");
        int sortingId = jsonObject.containsKey("sortingId") ? jsonObject.getInt("sortingId") : 0;
        int fontSize = jsonObject.containsKey("fontSize") ? jsonObject.getInt("fontSize") : 10;
        settingsService.updateSettings(showDate, ascending, sortingId, fontSize);
    }
    return "{}";
}
 
Example 2
Source File: ObjectHandler.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Called by Gluon CloudLink when a new object is added. This implementation will update the Settings object in the
 * database.
 *
 * @param objectIdentifier the identifier of the object that is added
 * @param payload the raw JSON payload of the object that is added
 * @return an empty response, as the response is ignored by Gluon CloudLink
 */
@POST
@Path("/add")
@Consumes(MediaType.APPLICATION_JSON + "; " + CHARSET)
@Produces(MediaType.APPLICATION_JSON + "; " + CHARSET)
public String addObject(@PathParam("objectIdentifier") String objectIdentifier,
                        String payload) {
    LOG.log(Level.INFO, "Added object with id " + objectIdentifier + ": " + payload);
    try (JsonReader jsonReader = Json.createReader(new StringReader(payload))) {
        JsonObject jsonObject = jsonReader.readObject();
        boolean showDate = !jsonObject.containsKey("showDate") || jsonObject.getBoolean("showDate");
        boolean ascending = !jsonObject.containsKey("ascending") || jsonObject.getBoolean("ascending");
        int sortingId = jsonObject.containsKey("sortingId") ? jsonObject.getInt("sortingId") : 0;
        int fontSize = jsonObject.containsKey("fontSize") ? jsonObject.getInt("fontSize") : 10;
        settingsService.updateSettings(showDate, ascending, sortingId, fontSize);
    }
    return "{}";
}
 
Example 3
Source File: TestSiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testPortStatus() throws IOException, InitializationException {
    ProcessGroupStatus pgStatus = generateProcessGroupStatus("root", "Awesome", 1, 0);

    final Map<PropertyDescriptor, String> properties = new HashMap<>();
    properties.put(SiteToSiteUtils.BATCH_SIZE, "4");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_NAME_FILTER_REGEX, "Awesome.*");
    properties.put(SiteToSiteStatusReportingTask.COMPONENT_TYPE_FILTER_REGEX, "(InputPort)");
    properties.put(SiteToSiteStatusReportingTask.ALLOW_NULL_VALUES,"false");

    MockSiteToSiteStatusReportingTask task = initTask(properties, pgStatus);
    task.onTrigger(context);

    final String msg = new String(task.dataSent.get(0), StandardCharsets.UTF_8);
    JsonReader jsonReader = Json.createReader(new ByteArrayInputStream(msg.getBytes()));
    JsonObject object = jsonReader.readArray().getJsonObject(0);
    JsonString runStatus = object.getJsonString("runStatus");
    assertEquals(RunStatus.Stopped.name(), runStatus.getString());
    boolean isTransmitting = object.getBoolean("transmitting");
    assertFalse(isTransmitting);
    JsonNumber inputBytes = object.getJsonNumber("inputBytes");
    assertEquals(5, inputBytes.intValue());
    assertNull(object.get("activeThreadCount"));
}
 
Example 4
Source File: JsonConverter.java    From junit-json-params with Apache License 2.0 6 votes vote down vote up
/**
 * Convert the supplied {@code source} object according to the supplied
 * {@code context}.
 *
 * @param source  the source object to convert; may be {@code null}
 * @param context the parameter context where the converted object will be
 *                used; never {@code null}
 * @return the converted object; may be {@code null} but only if the target
 * type is a reference type
 * @throws ArgumentConversionException if an error occurs during the
 *                                     conversion
 */
@Override
public Object convert(Object source, ParameterContext context) {
    if (!(source instanceof JsonObject)) {
        throw new ArgumentConversionException("Not a JsonObject");
    }
    JsonObject json = (JsonObject) source;
    String name = context.getParameter().getName();
    Class<?> type = context.getParameter().getType();
    if (type == String.class) {
        return json.getString(name);
    } else if (type == int.class) {
        return json.getInt(name);
    } else if (type == boolean.class) {
        return json.getBoolean(name);
    }
    throw new ArgumentConversionException("Can't convert to type: '" + type.getName() + "'");
}
 
Example 5
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 6
Source File: ColumnAdapterNotes.java    From hadoop-etl-udfs with MIT License 6 votes vote down vote up
public static ColumnAdapterNotes deserialize(String columnAdapterNotes, String columnName) {
    if (columnAdapterNotes == null || columnAdapterNotes.isEmpty()) {
        throw new RuntimeException(getException(columnName));
    }
    JsonObject root;
    try {
        root = JsonHelper.getJsonObject(columnAdapterNotes);
    } catch (Exception ex) {
        throw new RuntimeException(getException(columnName));
    }
    checkKey(root, "originalTypeName", columnName);
    checkKey(root, "partitionedColumn", columnName);
    return new ColumnAdapterNotes(
            root.getString("originalTypeName"),
            root.getBoolean("partitionedColumn")
    );
}
 
Example 7
Source File: User.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
/** Constructor for reading the user from the JSON that was a part of a JAX-RS request. */
public User(JsonObject user) {
  if (user.containsKey(JSON_KEY_USER_ID)) {
    id = user.getString(JSON_KEY_USER_ID);
  }
  this.firstName = user.getString(JSON_KEY_USER_FIRST_NAME, "");
  this.lastName = user.getString(JSON_KEY_USER_LAST_NAME, "");
  this.twitterHandle = user.getString(JSON_KEY_USER_TWITTER_HANDLE, "");
  this.wishListLink = user.getString(JSON_KEY_USER_WISH_LIST_LINK, "");
  this.isTwitterLogin = user.getBoolean(JSON_KEY_USER_TWITTER_LOGIN, false);

  if (user.containsKey(JSON_KEY_USER_NAME)) {
    this.userName = user.getString(JSON_KEY_USER_NAME);
  }
  if (user.containsKey(JSON_KEY_USER_PASSWORD_HASH)) {
    this.passwordHash = user.getString(JSON_KEY_USER_PASSWORD_HASH);
  }
  if (user.containsKey(JSON_KEY_USER_PASSWORD_SALT)) {
    this.passwordSalt = user.getString(JSON_KEY_USER_PASSWORD_SALT);
  }
}
 
Example 8
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 9
Source File: MessageCounterInfo.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a MessageCounterInfo corresponding to the JSON serialization returned
 * by {@link QueueControl#listMessageCounter()}.
 */
public static MessageCounterInfo fromJSON(final String jsonString) throws Exception {
   JsonObject data = JsonUtil.readJsonObject(jsonString);
   String name = data.getString("destinationName");
   String subscription = data.getString("destinationSubscription", null);
   boolean durable = data.getBoolean("destinationDurable");
   long count = data.getJsonNumber("count").longValue();
   long countDelta = data.getJsonNumber("countDelta").longValue();
   int depth = data.getInt("messageCount");
   int depthDelta = data.getInt("messageCountDelta");
   String lastAddTimestamp = data.getString("lastAddTimestamp");
   String updateTimestamp = data.getString("updateTimestamp");

   return new MessageCounterInfo(name, subscription, durable, count, countDelta, depth, depthDelta, lastAddTimestamp, updateTimestamp);
}
 
Example 10
Source File: skfsCommon.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Boolean handleNonExistantJsonBoolean(JsonObject jsonObject, String key) {
    try {
        return jsonObject.getBoolean(key);
    } catch (NullPointerException ex) {
        return null;
    }
}
 
Example 11
Source File: RoleInfo.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an array of RoleInfo corresponding to the JSON serialization returned
 * by {@link AddressControl#getRolesAsJSON()}.
 */
public static RoleInfo[] from(final String jsonString) throws Exception {
   JsonArray array = JsonUtil.readJsonArray(jsonString);
   RoleInfo[] roles = new RoleInfo[array.size()];
   for (int i = 0; i < array.size(); i++) {
      JsonObject r = array.getJsonObject(i);
      RoleInfo role = new RoleInfo(r.getString("name"), r.getBoolean("send"), r.getBoolean("consume"), r.getBoolean("createDurableQueue"), r.getBoolean("deleteDurableQueue"), r.getBoolean("createNonDurableQueue"), r.getBoolean("deleteNonDurableQueue"), r.getBoolean("manage"), r.getBoolean("browse"), r.getBoolean("createAddress"));
      roles[i] = role;
   }
   return roles;
}
 
Example 12
Source File: SystemInputJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the value definition represented by the given JSON object.
 */
private static VarValueDef asValueDef( String valueName, JsonObject json)
  {
  try
    {
    VarValueDef valueDef = new VarValueDef( ObjectUtils.toObject( valueName));

    // Get the type of this value
    boolean failure = json.getBoolean( FAILURE_KEY, false);
    boolean once = json.getBoolean( ONCE_KEY, false);
    valueDef.setType
      ( failure? VarValueDef.Type.FAILURE :
        once? VarValueDef.Type.ONCE :
        VarValueDef.Type.VALID);

    if( failure && json.containsKey( PROPERTIES_KEY))
      {
      throw new SystemInputException( "Failure type values can't define properties");
      }

    // Get annotations for this value
    Optional.ofNullable( json.getJsonObject( HAS_KEY))
      .ifPresent( has -> has.keySet().stream().forEach( key -> valueDef.setAnnotation( key, has.getString( key))));
  
    // Get the condition for this value
    Optional.ofNullable( json.getJsonObject( WHEN_KEY))
      .ifPresent( object -> valueDef.setCondition( asValidCondition( object)));

    // Get properties for this value
    Optional.ofNullable( json.getJsonArray( PROPERTIES_KEY))
      .map( properties -> toIdentifiers( properties)) 
      .ifPresent( properties -> valueDef.addProperties( properties)); 

    return valueDef;
    }
  catch( SystemInputException e)
    {
    throw new SystemInputException( String.format( "Error defining value=%s", valueName), e);
    }
  }
 
Example 13
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 14
Source File: TerminalConfigBean.java    From AsciidocFX with Apache License 2.0 4 votes vote down vote up
@Override
public void load(Path configPath, ActionEvent... actionEvent) {

    fadeOut(infoLabel, "Loading...");

    Reader fileReader = IOHelper.fileReader(configPath);
    JsonReader jsonReader = Json.createReader(fileReader);

    JsonObject jsonObject = jsonReader.readObject();

    String terminalWinCommand = jsonObject.getString("terminalWinCommand", this.terminalWinCommand.getValue());
    String terminalNixCommand = jsonObject.getString("terminalNixCommand", this.terminalNixCommand.getValue());
    String backgroundColor = jsonObject.getString("backgroundColor", FxHelper.colorToHex(this.backgroundColor.getValue()));
    String cursorColor = jsonObject.getString("cursorColor", FxHelper.colorToHex(this.backgroundColor.getValue()));
    String foregroundColor = jsonObject.getString("foregroundColor", FxHelper.colorToHex(this.backgroundColor.getValue()));
    Boolean clearSelectionAfterCopy = jsonObject.getBoolean("clearSelectionAfterCopy", this.clearSelectionAfterCopy.getValue());
    Boolean copyOnSelect = jsonObject.getBoolean("copyOnSelect", this.copyOnSelect.getValue());
    Boolean ctrlCCopy = jsonObject.getBoolean("ctrlCCopy", this.ctrlCCopy.getValue());
    Boolean ctrlVPaste = jsonObject.getBoolean("ctrlVPaste", this.ctrlVPaste.getValue());
    Boolean cursorBlink = jsonObject.getBoolean("cursorBlink", this.cursorBlink.getValue());
    Boolean enableClipboardNotice = jsonObject.getBoolean("enableClipboardNotice", this.enableClipboardNotice.getValue());
    Boolean scrollbarVisible = jsonObject.getBoolean("scrollbarVisible", this.scrollbarVisible.getValue());
    Boolean useDefaultWindowCopy = jsonObject.getBoolean("useDefaultWindowCopy", this.useDefaultWindowCopy.getValue());
    String fontFamily = jsonObject.getString("fontFamily", this.fontFamily.getValue());
    Integer fontSize = jsonObject.getInt("fontSize", this.fontSize.getValue());
    String receiveEncoding = jsonObject.getString("receiveEncoding", this.receiveEncoding.getValue());
    String sendEncoding = jsonObject.getString("sendEncoding", this.sendEncoding.getValue());
    String userCss = jsonObject.getString("userCss", this.userCss.getValue());

    IOHelper.close(jsonReader, fileReader);

    threadService.runActionLater(() -> {

        this.setTerminalWinCommand(terminalWinCommand);
        this.setTerminalNixCommand(terminalNixCommand);
        this.setBackgroundColor(Color.web(backgroundColor));
        this.setCursorColor(Color.web(cursorColor));
        this.setForegroundColor(Color.web(foregroundColor));
        this.setClearSelectionAfterCopy(clearSelectionAfterCopy);
        this.setCopyOnSelect(copyOnSelect);
        this.setCtrlCCopy(ctrlCCopy);
        this.setCtrlVPaste(ctrlVPaste);
        this.setCursorBlink(cursorBlink);
        this.setEnableClipboardNotice(enableClipboardNotice);
        this.setScrollbarVisible(scrollbarVisible);
        this.setUseDefaultWindowCopy(useDefaultWindowCopy);
        this.setFontFamily(fontFamily);
        this.setFontSize(fontSize);
        this.setReceiveEncoding(receiveEncoding);
        this.setSendEncoding(sendEncoding);
        this.setUserCss(userCss);

        if (jsonObject.containsKey("scrollWhellMoveMultiplier")) {
            this.setScrollWhellMoveMultiplier(jsonObject.getJsonNumber("scrollWhellMoveMultiplier").doubleValue());
        }

        fadeOut(infoLabel, "Loaded...");

    });
}
 
Example 15
Source File: WeiboStatus.java    From albert with MIT License 4 votes vote down vote up
private void constructJson(JsonObject json) throws WeiboException {
	try {
		createdAt = WeiboResponseUtil.parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
		id = json.getJsonNumber("id").longValue();
		mid = json.getString("mid");
		idstr = json.getString("idstr");
		text = WeiboResponseUtil.withNonBmpStripped(json.getString("text"));
		if (!json.getString("source").isEmpty()) {
			source = new Source(WeiboResponseUtil.withNonBmpStripped(json.getString("source")));
		}
		inReplyToStatusId = json.getString("in_reply_to_status_id");
		inReplyToUserId = json.getString("in_reply_to_user_id");
		inReplyToScreenName = json.getString("in_reply_to_screen_name");
		favorited = json.getBoolean("favorited");
		truncated = json.getBoolean("truncated");
		thumbnailPic = JsonUtil.getString(json, "thumbnail_pic");
		bmiddlePic = JsonUtil.getString(json, "bmiddle_pic");
		originalPic = JsonUtil.getString(json, "original_pic");
		repostsCount = json.getInt("reposts_count");
		commentsCount = json.getInt("comments_count");
		if (json.containsKey("annotations"))
			annotations = json.getJsonArray("annotations").toString();
		if (!json.isNull("user"))
			weiboUser = new WeiboUser(json.getJsonObject("user"));
		if (json.containsKey("retweeted_status")) {
			retweetedStatus = new WeiboStatus(json.getJsonObject("retweeted_status"));
		}
		mlevel = json.getInt("mlevel");
		if (json.isNull("geo")) {
			geo = null;
		} else {
			geo = json.getJsonObject("geo").toString();
		}
		if (geo != null && !"".equals(geo) && !"null".equals(geo)) {
			getGeoInfo(geo);
		}
		if (!json.isNull("visible")) {
			visible = new Visible(json.getJsonObject("visible"));
		}
	} catch (JsonException je) {
		throw new WeiboException(je.getMessage() + ":" + json.toString(), je);
	}
}
 
Example 16
Source File: CodeGenerator.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private boolean isSummary(JsonObject elementDefinition) {
    return elementDefinition.getBoolean("isSummary", false);
}
 
Example 17
Source File: VerifyRecaptcha.java    From journaldev with MIT License 4 votes vote down vote up
public static boolean verify(String gRecaptchaResponse) throws IOException {
	if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
		return false;
	}
	
	try{
	URL obj = new URL(url);
	HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

	// add reuqest header
	con.setRequestMethod("POST");
	con.setRequestProperty("User-Agent", USER_AGENT);
	con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

	String postParams = "secret=" + secret + "&response="
			+ gRecaptchaResponse;

	// Send post request
	con.setDoOutput(true);
	DataOutputStream wr = new DataOutputStream(con.getOutputStream());
	wr.writeBytes(postParams);
	wr.flush();
	wr.close();

	int responseCode = con.getResponseCode();
	System.out.println("\nSending 'POST' request to URL : " + url);
	System.out.println("Post parameters : " + postParams);
	System.out.println("Response Code : " + responseCode);

	BufferedReader in = new BufferedReader(new InputStreamReader(
			con.getInputStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();

	while ((inputLine = in.readLine()) != null) {
		response.append(inputLine);
	}
	in.close();

	// print result
	System.out.println(response.toString());
	
	//parse JSON response and return 'success' value
	JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
	JsonObject jsonObject = jsonReader.readObject();
	jsonReader.close();
	
	return jsonObject.getBoolean("success");
	}catch(Exception e){
		e.printStackTrace();
		return false;
	}
}
 
Example 18
Source File: CodeGenerator.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private boolean isAbstract(JsonObject structureDefinition) {
    return structureDefinition.getBoolean("abstract", false);
}
 
Example 19
Source File: applianceCommon.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Given a JSON string and a search-key, this method looks up the 'key' in
 * the JSON and if found, returns the associated value. Returns NULL in all
 * error conditions.
 *
 * @param jsonstr String containing JSON
 * @param key String containing the search-key
 * @param datatype String containing the data-type of the value-object
 * @return Object containing the value for the specified key if valid; null
 * in all error cases.
 */
public static Object getJsonValue(String jsonstr, String key, String datatype) {
    if (jsonstr == null || jsonstr.isEmpty()) {
        if (key == null || key.isEmpty()) {
            if (datatype == null || datatype.isEmpty()) {
                return null;
            }
        }
    }

    try (JsonReader jsonreader = Json.createReader(new StringReader(jsonstr))) {
        JsonObject json = jsonreader.readObject();

        if (!json.containsKey(key)) {
            strongkeyLogger.log(applianceConstants.APPLIANCE_LOGGER, Level.FINE, "APPL-ERR-1003", "'" + key + "' does not exist in the json");
            return null;
        }

        switch (datatype) {
            case "Boolean":
                return json.getBoolean(key);
            case "Int":
                return json.getInt(key);
            case "Long":
                return json.getJsonNumber(key).longValueExact();
            case "JsonArray":
                return json.getJsonArray(key);
            case "JsonNumber":
                return json.getJsonNumber(key);
            case "JsonObject":
                return json.getJsonObject(key);
            case "JsonString":
                return json.getJsonString(key);
            case "String":
                return json.getString(key);
            default:
                return null;
        }
    } catch (Exception ex) {
        strongkeyLogger.log(applianceConstants.APPLIANCE_LOGGER, Level.WARNING, "APPL-ERR-1000", ex.getLocalizedMessage());
        return null;
    }
}
 
Example 20
Source File: Utils.java    From KITE with Apache License 2.0 3 votes vote down vote up
/**
 * Gets the boolean value from a given json object,
 * overwrite it with System env or a default value if applicable
 *
 * @param jsonObject   the json object
 * @param key          name of the attribute
 * @param defaultValue default value
 *
 * @return an Boolean value
 */
public static boolean getBooleanFromJsonObject(JsonObject jsonObject, String key, boolean defaultValue) {
  if (System.getProperty(key) == null) {
    return jsonObject.getBoolean(key, defaultValue);
  } else {
    return Boolean.parseBoolean(System.getProperty(key));
  }
}