Java Code Examples for com.fasterxml.jackson.databind.JsonNode#asText()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#asText() . 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: AbstractTaskQueryResource.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
private void handleAssignment(TaskInfoQueryWrapper taskInfoQueryWrapper, JsonNode assignmentNode, User currentUser) {
  String assignment = assignmentNode.asText();
  if (assignment.length() > 0) {
    String currentUserId = String.valueOf(currentUser.getId());
    if ("assignee".equals(assignment)) {
      taskInfoQueryWrapper.getTaskInfoQuery().taskAssignee(currentUserId);
    } else if ("candidate".equals(assignment)) {
      taskInfoQueryWrapper.getTaskInfoQuery().taskCandidateUser(currentUserId);
    } else if (assignment.startsWith("group_")) {
      String groupIdString = assignment.replace("group_", "");
      try {
        Long.valueOf(groupIdString);
      } catch (NumberFormatException e) {
        throw new BadRequestException("Invalid group id");
      }
      taskInfoQueryWrapper.getTaskInfoQuery().taskCandidateGroup(groupIdString);
    } else { // Default = involved
      taskInfoQueryWrapper.getTaskInfoQuery().taskInvolvedUser(currentUserId);
    }
  }
}
 
Example 2
Source File: CayenneExpParser.java    From agrest with Apache License 2.0 6 votes vote down vote up
/**
 * @since 2.13
 */
@Override
public CayenneExp fromJson(JsonNode json) {

    if (json == null || json.isNull()) {
        return null;
    }

    if(json.isTextual()) {
        return new CayenneExp(json.asText());
    }

    if(json.isArray()) {
        return fromJsonArray(json);
    }

    if(json.isObject()) {
        return fromJsonObject(json);
    }

    // TODO: throw?
    return null;
}
 
Example 3
Source File: JsonNodeLinker.java    From yql-plus with Apache License 2.0 6 votes vote down vote up
public static Object readProperty(JsonNode node, String property) throws IOException {
    JsonNode result = node.get(property);
    if (result == null) {
        return null;
    }
    switch (result.getNodeType()) {
        case NUMBER:
            return result.numberValue();
        case BOOLEAN:
            return result.booleanValue();
        case NULL:
            return null;
        case STRING:
            return result.asText();
        case BINARY:
            return ByteBuffer.wrap(result.binaryValue());
        case MISSING:
        case OBJECT:
        case POJO:
        case ARRAY:
        default:
            return result;
    }

}
 
Example 4
Source File: AuditLogEntryImpl.java    From Javacord with Apache License 2.0 5 votes vote down vote up
private AuditLogChange<?> iconChange(String baseUrl, AuditLogChangeType type, JsonNode oldVal, JsonNode newVal) {
    try {
        Icon oldIcon = oldVal != null ? new IconImpl(getApi(), new URL(baseUrl + getTarget()
                .map(DiscordEntity::getIdAsString).orElse("0") + "/" + oldVal.asText() + ".png")) : null;
        Icon newIcon = newVal != null ? new IconImpl(getApi(), new URL(baseUrl + getTarget()
                .map(DiscordEntity::getIdAsString).orElse("0") + "/" + newVal.asText() + ".png")) : null;
        return new AuditLogChangeImpl<>(type, oldIcon, newIcon);
    } catch (MalformedURLException e) {
        logger.warn("Seems like the icon's url is malformed! Please contact the developer!", e);
        return new AuditLogChangeImpl<>(AuditLogChangeType.UNKNOWN, oldVal, newVal);
    }
}
 
Example 5
Source File: WorkflowParser.java    From cwlexec with Apache License 2.0 5 votes vote down vote up
private static Object toDefaultObjectValue(String descTop,
        String id,
        JsonNode defaultNode) throws CWLException {
    JsonNode classNode = defaultNode.get(CLASS);
    if (classNode != null && classNode.isTextual()) {
        String clazz = classNode.asText();
        if ("File".equals(clazz)) {
            return processCWLFile(descTop, id, defaultNode, true);
        } else if ("Directory".equals(clazz)) {
            return processCWLDirectory(descTop, id, defaultNode, true);
        }
    }
    return null;
}
 
Example 6
Source File: BaseBpmnJsonConverter.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected String getValueAsString(String name, JsonNode objectNode) {
  String propertyValue = null;
  JsonNode propertyNode = objectNode.get(name);
  if (propertyNode != null && propertyNode.isNull() == false) {
    propertyValue = propertyNode.asText();
  }
  return propertyValue;
}
 
Example 7
Source File: Player.java    From Kore with Apache License 2.0 5 votes vote down vote up
public String getTitle() {
    JsonNode jsonNode = itemNode.get(TITLE);
    if (jsonNode != null)
        return jsonNode.asText();
    else
        return null;
}
 
Example 8
Source File: JsonSerializer.java    From workflow with Apache License 2.0 5 votes vote down vote up
static TaskExecutionResult getTaskExecutionResult(JsonNode node)
{
    JsonNode subTaskRunIdNode = node.get("subTaskRunId");
    return new TaskExecutionResult
    (
        TaskExecutionStatus.valueOf(node.get("status").asText().toUpperCase()),
        node.get("message").asText(),
        getMap(node.get("resultData")),
        ((subTaskRunIdNode != null) && !subTaskRunIdNode.isNull()) ? new RunId(subTaskRunIdNode.asText()) : null,
        LocalDateTime.parse(node.get("completionTimeUtc").asText(), DateTimeFormatter.ISO_DATE_TIME)
    );
}
 
Example 9
Source File: ContentPredicates.java    From template-compiler with Apache License 2.0 5 votes vote down vote up
@Override
public boolean apply(Context ctx, Arguments args) throws CodeExecuteException {
  JsonNode excerpt = ctx.node().path("excerpt");
  JsonNode html = excerpt.path("html");
  String text = "";
  if (html.isTextual()) {
    text = html.asText();
  } else if (excerpt.isTextual()) {
    text = excerpt.asText();
  }
  text = PluginUtils.removeTags(text);
  text = Patterns.WHITESPACE_NBSP.matcher(text).replaceAll("");
  return text.length() > 0;
}
 
Example 10
Source File: AlarmCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Alarm decode(ObjectNode json, CodecContext context) {
    if (json == null || !json.isObject()) {
        return null;
    }

    log.debug("id={}, full json={} ", json.get("id"), json);
    String id = json.get("id").asText();

    DeviceId deviceId = DeviceId.deviceId(json.get("deviceId").asText());
    String description = json.get("description").asText();
    Long timeRaised = json.get("timeRaised").asLong();
    Long timeUpdated = json.get("timeUpdated").asLong();

    JsonNode jsonTimeCleared = json.get("timeCleared");
    Long timeCleared = jsonTimeCleared == null || jsonTimeCleared.isNull() ? null : jsonTimeCleared.asLong();

    Alarm.SeverityLevel severity = Alarm.SeverityLevel.valueOf(json.get("severity").asText().toUpperCase());

    Boolean serviceAffecting = json.get("serviceAffecting").asBoolean();
    Boolean acknowledged = json.get("acknowledged").asBoolean();
    Boolean manuallyClearable = json.get("manuallyClearable").asBoolean();

    JsonNode jsonAssignedUser = json.get("assignedUser");
    String assignedUser
            = jsonAssignedUser == null || jsonAssignedUser.isNull() ? null : jsonAssignedUser.asText();

    return new DefaultAlarm.Builder(AlarmId.alarmId(deviceId, id),
            deviceId, description, severity, timeRaised).forSource(AlarmEntityId.NONE)
            .withTimeUpdated(timeUpdated)
            .withTimeCleared(timeCleared)
            .withServiceAffecting(serviceAffecting)
            .withAcknowledged(acknowledged)
            .withManuallyClearable(manuallyClearable)
            .withAssignedUser(assignedUser)
            .build();

}
 
Example 11
Source File: CustomMetaSchemaTest.java    From json-schema-validator with Apache License 2.0 5 votes vote down vote up
@Override
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
    String value = node.asText();
    int idx = enumValues.indexOf(value);
    if (idx < 0) {
        throw new IllegalArgumentException("value not found in enum. value: " + value + " enum: " + enumValues);
    }
    String valueName = enumNames.get(idx);
    return fail(CustomErrorMessageType.of("tests.example.enumNames", new MessageFormat("{0}: enumName is {1}")), at, valueName);
}
 
Example 12
Source File: AbstractTaskQueryResource.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
private void handleTextFiltering(TaskInfoQueryWrapper taskInfoQueryWrapper, JsonNode textNode) {
  String text = textNode.asText();

  // [4/9/2014] Used to be an or on description too, but doesnt work combined with the or query for an app.
  // (Would need a change in Activiti)
  taskInfoQueryWrapper.getTaskInfoQuery().taskNameLikeIgnoreCase("%" + text + "%");
}
 
Example 13
Source File: BaseParser.java    From cwlexec with Apache License 2.0 5 votes vote down vote up
protected static String processStringField(String key, JsonNode stringNode) throws CWLException {
    String str = null;
    if (stringNode != null) {
        if (stringNode.isTextual()) {
            str = stringNode.asText();
        } else {
            throw new CWLException(
                    ResourceLoader.getMessage(CWL_PARSER_INVALID_TYPE, key, CWLTypeSymbol.STRING),
                    251);
        }
    }
    return str;
}
 
Example 14
Source File: BitlibJsonModule.java    From bitshares_wallet with MIT License 5 votes vote down vote up
@Override
public PublicKey deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
   ObjectCodec oc = jp.getCodec();
   JsonNode node = oc.readTree(jp);
   byte[] pubKeyBytes;
   try {
      pubKeyBytes = HexUtils.toBytes(node.asText());
   } catch (RuntimeException e) {
      throw new JsonParseException("Failed to convert string '" + node.asText() + "' into an public key bytes",
            JsonLocation.NA);
   }
   return new PublicKey(pubKeyBytes);
}
 
Example 15
Source File: FreegeoipProvider.java    From play-geolocation-module.edulify.com with Apache License 2.0 5 votes vote down vote up
private Geolocation asGeolocation(JsonNode json) {
  JsonNode jsonIp          = json.get("ip");
  JsonNode jsonCountryCode = json.get("country_code");
  JsonNode jsonCountryName = json.get("country_name");
  JsonNode jsonRegionCode  = json.get("region_code");
  JsonNode jsonRegionName  = json.get("region_name");
  JsonNode jsonCity        = json.get("city");
  JsonNode jsonLatitude    = json.get("latitude");
  JsonNode jsonLongitude   = json.get("longitude");
  JsonNode jsonTimeZone    = json.get("time_zone");

  if (jsonIp          == null ||
      jsonCountryCode == null ||
      jsonCountryName == null ||
      jsonRegionCode  == null ||
      jsonRegionName  == null ||
      jsonCity        == null ||
      jsonLatitude    == null ||
      jsonLongitude   == null ||
      jsonTimeZone    == null) {
    return Geolocation.empty();
  }

  return new Geolocation(
      jsonIp.asText(),
      jsonCountryCode.asText(),
      jsonCountryName.asText(),
      jsonRegionCode.asText(),
      jsonRegionName.asText(),
      jsonCity.asText(),
      jsonLatitude.asDouble(),
      jsonLongitude.asDouble(),
      jsonTimeZone.asText()
  );
}
 
Example 16
Source File: AmalgamatedKey.java    From bidder with Apache License 2.0 5 votes vote down vote up
/**
 * Return a JsonNode value as a key
 * @param obj Object.
 * @return
 */
public static String asString(Object obj) {
    if (obj == null)
        return null;

    if (obj instanceof JsonNode == false)
        return obj.toString();

    JsonNode node = (JsonNode)obj;
    if (node instanceof MissingNode)
        return null;
    return node.asText();
}
 
Example 17
Source File: SerializationDeserializationFeatureUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenFailOnUnkownPropertiesFalse_thanJsonReadCorrectly() throws Exception {

    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    final Car car = objectMapper.readValue(JSON_CAR, Car.class);
    final JsonNode jsonNodeRoot = objectMapper.readTree(JSON_CAR);
    final JsonNode jsonNodeYear = jsonNodeRoot.get("year");
    final String year = jsonNodeYear.asText();

    assertNotNull(car);
    assertThat(car.getColor(), equalTo("Black"));
    assertThat(year, containsString("1970"));
}
 
Example 18
Source File: JsonConfigConverter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static ModelNode theme(JsonNode root, PathAddress addr) {
    JsonNode themeNode = getNode(root, "theme");
    ModelNode op = Util.createAddOperation(addr);
    
    JsonNode targetNode = getNode(themeNode, "staticMaxAge");
    Long lValue = STATIC_MAX_AGE.getDefaultValue().asLong();
    if (targetNode != null) lValue = targetNode.asLong(lValue);
    op.get(STATIC_MAX_AGE.getName()).set(lValue);

    targetNode = getNode(themeNode, "cacheTemplates");
    Boolean bValue = CACHE_TEMPLATES.getDefaultValue().asBoolean();
    if (targetNode != null) bValue = targetNode.asBoolean(bValue);
    op.get(CACHE_TEMPLATES.getName()).set(bValue);
    
    targetNode = getNode(themeNode, "cacheThemes");
    bValue = CACHE_THEMES.getDefaultValue().asBoolean();
    if (targetNode != null) bValue = targetNode.asBoolean(bValue);
    op.get(CACHE_THEMES.getName()).set(bValue);
    
    targetNode = getNode(themeNode, "folder", "dir");
    String sValue = DIR.getDefaultValue().asString();
    if (targetNode != null) sValue = targetNode.asText(sValue);
    op.get(DIR.getName()).set(sValue);
    
    targetNode = getNode(themeNode, "welcomeTheme");
    if (targetNode != null) op.get(WELCOME_THEME.getName()).set(targetNode.asText());
    
    targetNode = getNode(themeNode, "default");
    if (targetNode != null) op.get(DEFAULT.getName()).set(targetNode.asText());
    
    targetNode = getNode(themeNode, "module", "modules");
    if (targetNode != null && targetNode.isArray()) {
        op.get(MODULES.getName()).set(themeModules(targetNode));
    }
    
    return op;
}
 
Example 19
Source File: ItemType.java    From Kore with Apache License 2.0 5 votes vote down vote up
public DetailsBase(JsonNode node) {
    JsonNode labelNode = node.get(LABEL);
    if (labelNode != null)
        label = labelNode.asText();
    else
        label = null;
}
 
Example 20
Source File: AbstractYMLConfigurationAction.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void execute() throws Exception {

	JsonNode node = provider.getRootNode();
	boolean isMultiModule = node.has("modules");
	if (recursive && isMultiModule) {

		JsonNode aux = node.get("modules");
		if (aux.isArray()) {
			ArrayNode modules = (ArrayNode) aux;
			int max = modules.size();
			for (int i = 0; i < max; i++) {
				JsonNode module = modules.get(i);
				if (module.isTextual()) {
					String moduleDir = module.asText();

					try {
						File auxFile = new File(provider.getFileName()).getCanonicalFile().getParentFile();
						YAMLConfigurationProvider child = new YAMLConfigurationProvider(auxFile.getAbsolutePath()
								+ File.separator + moduleDir + File.separator + "walkmod.yml");
						child.createConfig();

						AbstractYMLConfigurationAction childAction = clone(child, recursive);
						childAction.execute();

					} catch (IOException e) {
						throw new TransformerException(e);
					}

				}
			}
		}

	} else {
		doAction(node);
	}
}