Java Code Examples for org.codehaus.jackson.JsonNode#asText()

The following examples show how to use org.codehaus.jackson.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: JsonCreateWebServer.java    From jwala with Apache License 2.0 6 votes vote down vote up
@Override
public JsonCreateWebServer deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException {

    final ObjectCodec obj = jp.getCodec();
    final JsonNode node = obj.readTree(jp).get(0);

    final JsonNode apacheHttpdMediaId = node.get("apacheHttpdMediaId");
    final JsonCreateWebServer jcws = new JsonCreateWebServer(node.get("webserverName").getTextValue(),
            node.get("hostName").getTextValue(),
            node.get("portNumber").asText(),
            node.get("httpsPort").asText(),
               deserializeGroupIdentifiers(node),
            node.get("statusPath").getTextValue(),
            apacheHttpdMediaId == null ? null : apacheHttpdMediaId.asText());
    return jcws;
}
 
Example 2
Source File: KubernetesBackUpTask.java    From kardio with Apache License 2.0 5 votes vote down vote up
/**
 * This function returns the Health check url for the service
 * @param ingressNode
 * @param healthCheckPort
 * @param pathValue
 * @return
 */
private static String getHealthCheckUrl(JsonNode ingressNode, String healthCheckPort, String pathValue) {
	// TODO Auto-generated method stub
	 JsonNode metadataNode = ingressNode.get("metadata");
     JsonNode annotNode = metadataNode.get("annotations");
     JsonNode namespaceNode = metadataNode.get("namespace");
     JsonNode nameNode = metadataNode.get("name");
     String ingressName = nameNode.asText();
     String namespace = namespaceNode.asText();
     /*The below block of code is for checking path based routing
      *CASE:: We are using nginx controller,below is the logic to find the app is using path based routing or not
      * If the "nginx.ingress.kubernetes.io/rewrite-target" is present in the annotation then app has path based routing */
     boolean isPathNeeded = false;
     String schemeValue = null;
        if(annotNode == null){
        	logger.info("The annotations node is null for the Ingress - "+ingressName+" in the namespace - "+ namespace);
        	isPathNeeded = false;
        }else{
        	isPathNeeded = annotNode.get("nginx.ingress.kubernetes.io/rewrite-target") == null? false : true;
        	schemeValue = annotNode.get("nginx.ingress.kubernetes.io/ssl-passthrough") == null ? null : "https";
        }
        
        JsonNode specIngNode = ingressNode.get("spec");
    	 JsonNode tlsNode = specIngNode.get("tls");
    	 if(schemeValue == null){
     		schemeValue = tlsNode == null ? "http" : "https";
     	 }
    	 String hostUrlPath = null;
        hostUrlPath =  getHostUrlAndPath(specIngNode, healthCheckPort, isPathNeeded);
        if(hostUrlPath == null){
       	 return null;
        }
	return schemeValue+ "://" + hostUrlPath + pathValue;
}
 
Example 3
Source File: KubernetesBackUpTask.java    From kardio with Apache License 2.0 5 votes vote down vote up
/**
 * This function returns the host url.
 * If the app is using path based routing, then path is appended to end of the host url 
 * @param specIngNode
 * @param healthCheckPort
 * @param isPathNeeded
 * @return
 */
private static String getHostUrlAndPath(JsonNode specIngNode, String healthCheckPort, boolean isPathNeeded) {
	// TODO Auto-generated method stub
	ArrayNode rulesArrayNode = (ArrayNode)specIngNode.get("rules");
   	Iterator<JsonNode> rulesNodeItr = rulesArrayNode.getElements();
   	while(rulesNodeItr.hasNext()){
   		JsonNode rulesNode = rulesNodeItr.next();
   		JsonNode hostNode = rulesNode.get("host");
   		if(hostNode == null){
   			return null;
   		}
   		String host = hostNode.asText();
   		if(!isPathNeeded){
   			return host;
   		}
   		JsonNode httpRuleNode = rulesNode.get("http");
   		ArrayNode pathsArrayNode = (ArrayNode)httpRuleNode.get("paths");
   		Iterator<JsonNode> pathsNodeItr = pathsArrayNode.getElements();
   		while(pathsNodeItr.hasNext()){
   			JsonNode pathsRootNode = pathsNodeItr.next();
   			JsonNode backendNode = pathsRootNode.get("backend");
   			JsonNode servicePortNode = backendNode.get("servicePort");
   			if(servicePortNode.asText().equals(healthCheckPort)){
   				JsonNode pathNode = pathsRootNode.get("path");
   				return host+pathNode.getTextValue();
   			}
   		}
   	}
   	return null;
}
 
Example 4
Source File: SocketServer.java    From tac2015-event-detection with GNU General Public License v3.0 5 votes vote down vote up
JsonNode runCommand(String command, String inputPayload) throws Exception {
	switch (command) {
	case "PARSEDOC":
		JsonNode input = JsonUtil.parse(inputPayload);
		String text = input.asText();
		return parser.processTextDocument(text);
	case "CRASH":
		throw new IOException("fake error");
	case "PING":
		return JsonUtil.toJson("PONG");
	default:
		throw new RuntimeException("bad command: " + command);
	}
}
 
Example 5
Source File: AutoJsonDeserializer.java    From kafka-metrics with Apache License 2.0 5 votes vote down vote up
public List<MeasurementV1> fromBytes(byte[] bytes) {
    try {
        JsonNode node = mapper.readTree(bytes);
        if (node.has("header") && node.has("metrics") && node.get("header").has("samza-version")) {
            return samzaDecoder.fromJsonTree(node);
        } else {
            throw new RuntimeJsonMappingException("Unrecoginzed JSON metric format: " + node.asText());
        }
    } catch (IOException e) {
        throw new RuntimeException("Error deserializing json object", e);
    }
}
 
Example 6
Source File: JsonConverterUtil.java    From fixflow with Apache License 2.0 5 votes vote down vote up
public static String getPropertyValueAsString(String name, JsonNode objectNode) {
  String propertyValue = null;
  JsonNode propertyNode = getProperty(name, objectNode);
  if (propertyNode != null && "null".equalsIgnoreCase(propertyNode.asText()) == false) {
    propertyValue = propertyNode.asText();
  }
  return propertyValue;
}
 
Example 7
Source File: JsonConverterUtil.java    From fixflow with Apache License 2.0 5 votes vote down vote up
public static List<String> getPropertyValueAsList(String name, JsonNode objectNode) {
  List<String> resultList = new ArrayList<String>();
  JsonNode propertyNode = getProperty(name, objectNode);
  if (propertyNode != null && "null".equalsIgnoreCase(propertyNode.asText()) == false) {
    String propertyValue = propertyNode.asText();
    String[] valueList = propertyValue.split(",");
    for (String value : valueList) {
      resultList.add(value.trim());
    }
  }
  return resultList;
}
 
Example 8
Source File: BpmnJsonConverterUtil.java    From fixflow with Apache License 2.0 5 votes vote down vote up
protected static String getPropertyValueAsString(String name, JsonNode objectNode) {
  String propertyValue = null;
  JsonNode propertyNode = getProperty(name, objectNode);
  if (propertyNode != null) {
    propertyValue = propertyNode.asText();
  }
  return propertyValue;
}
 
Example 9
Source File: BaseBpmnJsonConverter.java    From fixflow 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 && "null".equalsIgnoreCase(propertyNode.asText()) == false) {
    propertyValue = propertyNode.asText();
  }
  return propertyValue;
}
 
Example 10
Source File: SliTokenExtractor.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public Token extract(String response) {
    Preconditions.checkEmptyString(response,
            "Response body is incorrect. Can't extract a token from an empty string");
    JsonNode root;
    try {
        root = mapper.readTree(response);
        JsonNode token = root.findValue("access_token");
        return new Token(token.asText(), "", response);
        
    } catch (Exception e) {
        return null;
    }
}
 
Example 11
Source File: LinkDeserializer.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public Link deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    
    ObjectMapper mapper = (ObjectMapper) parser.getCodec();
    ObjectNode root = (ObjectNode) mapper.readTree(parser);
    
    JsonNode relNode = root.get("rel");
    JsonNode hrefNode = root.get("href");
    return new BasicLink(relNode.asText(), new URL(hrefNode.asText()));
}
 
Example 12
Source File: PubSub.java    From WAMPlay with MIT License 5 votes vote down vote up
/**
 * Method that truncates an event message before it's published. 
 * @param client WAMP client that sent the event
 * @param event Event to be truncated
 * @return Modified json event, null to halt publish
 */
@onPublish("truncate")
public static JsonNode truncatePublish(String sessionID, JsonNode event) {
	if (!event.isTextual()) {
		return cancel();
	}		
	String message = event.asText();
	if (message.length() > 10) {
		message = message.substring(0, MAX_MESSAGE_LENGTH);
	}
	return Json.toJson(message);
}
 
Example 13
Source File: ConvertJSONToSQL.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
private String generateInsert(final JsonNode rootNode, final Map<String, String> attributes, final String tableName,
                              final TableSchema schema, final boolean translateFieldNames, final boolean ignoreUnmappedFields, final boolean failUnmappedColumns,
                              final boolean warningUnmappedColumns, boolean escapeColumnNames, boolean quoteTableName) {

    final Set<String> normalizedFieldNames = getNormalizedColumnNames(rootNode, translateFieldNames);
    for (final String requiredColName : schema.getRequiredColumnNames()) {
        final String normalizedColName = normalizeColumnName(requiredColName, translateFieldNames);
        if (!normalizedFieldNames.contains(normalizedColName)) {
            String missingColMessage = "JSON does not have a value for the Required column '" + requiredColName + "'";
            if (failUnmappedColumns) {
                getLogger().error(missingColMessage);
                throw new ProcessException(missingColMessage);
            } else if (warningUnmappedColumns) {
                getLogger().warn(missingColMessage);
            }
        }
    }

    final StringBuilder sqlBuilder = new StringBuilder();
    int fieldCount = 0;
    sqlBuilder.append("INSERT INTO ");
    if (quoteTableName) {
        sqlBuilder.append(schema.getQuotedIdentifierString())
            .append(tableName)
            .append(schema.getQuotedIdentifierString());
    } else {
        sqlBuilder.append(tableName);
    }
    sqlBuilder.append(" (");

    // iterate over all of the elements in the JSON, building the SQL statement by adding the column names, as well as
    // adding the column value to a "sql.args.N.value" attribute and the type of a "sql.args.N.type" attribute add the
    // columns that we are inserting into
    final Iterator<String> fieldNames = rootNode.getFieldNames();
    while (fieldNames.hasNext()) {
        final String fieldName = fieldNames.next();

        final ColumnDescription desc = schema.getColumns().get(normalizeColumnName(fieldName, translateFieldNames));
        if (desc == null && !ignoreUnmappedFields) {
            throw new ProcessException("Cannot map JSON field '" + fieldName + "' to any column in the database");
        }

        if (desc != null) {
            if (fieldCount++ > 0) {
                sqlBuilder.append(", ");
            }

            if(escapeColumnNames){
                sqlBuilder.append(schema.getQuotedIdentifierString())
                    .append(desc.getColumnName())
                    .append(schema.getQuotedIdentifierString());
            } else {
                sqlBuilder.append(desc.getColumnName());
            }

            final int sqlType = desc.getDataType();
            attributes.put("sql.args." + fieldCount + ".type", String.valueOf(sqlType));

            final Integer colSize = desc.getColumnSize();
            final JsonNode fieldNode = rootNode.get(fieldName);
            if (!fieldNode.isNull()) {
                String fieldValue = fieldNode.asText();
                if (colSize != null && fieldValue.length() > colSize) {
                    fieldValue = fieldValue.substring(0, colSize);
                }
                attributes.put("sql.args." + fieldCount + ".value", fieldValue);
            }
        }
    }

    // complete the SQL statements by adding ?'s for all of the values to be escaped.
    sqlBuilder.append(") VALUES (");
    for (int i=0; i < fieldCount; i++) {
        if (i > 0) {
            sqlBuilder.append(", ");
        }

        sqlBuilder.append("?");
    }
    sqlBuilder.append(")");

    if (fieldCount == 0) {
        throw new ProcessException("None of the fields in the JSON map to the columns defined by the " + tableName + " table");
    }

    return sqlBuilder.toString();
}
 
Example 14
Source File: ConvertJSONToSQL.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 *  Try to create correct SQL String representation of value.
 *
 */
protected static String createSqlStringValue(final JsonNode fieldNode, final Integer colSize, final int sqlType) {
    String fieldValue = fieldNode.asText();

    switch (sqlType) {

    // only "true" is considered true, everything else is false
    case Types.BOOLEAN:
        fieldValue = Boolean.valueOf(fieldValue).toString();
        break;

    // Don't truncate numeric types.
    case Types.BIT:
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    case Types.BIGINT:
    case Types.REAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.DECIMAL:
    case Types.NUMERIC:
        if (fieldNode.isBoolean()) {
            // Convert boolean to number representation for databases those don't support boolean type.
            fieldValue = fieldNode.asBoolean() ? "1" : "0";
        }
        break;

    // Don't truncate DATE, TIME and TIMESTAMP types. We assume date and time is already correct in long representation.
    // Specifically, milliseconds since January 1, 1970, 00:00:00 GMT
    // However, for TIMESTAMP, PutSQL accepts optional timestamp format via FlowFile attribute.
    // See PutSQL.setParameter method and NIFI-3430 for detail.
    // Alternatively, user can use JSONTreeReader and PutDatabaseRecord to handle date format more efficiently.
    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
        break;

    // Truncate string data types only.
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    case Types.NCHAR:
    case Types.NVARCHAR:
    case Types.LONGNVARCHAR:
        if (colSize != null && fieldValue.length() > colSize) {
            fieldValue = fieldValue.substring(0, colSize);
        }
        break;
    }

    return fieldValue;
}
 
Example 15
Source File: ConvertJSONToSQL.java    From nifi with Apache License 2.0 4 votes vote down vote up
private String generateDelete(final JsonNode rootNode, final Map<String, String> attributes, final String tableName,
                              final TableSchema schema, final boolean translateFieldNames, final boolean ignoreUnmappedFields, final boolean failUnmappedColumns,
                              final boolean warningUnmappedColumns, boolean escapeColumnNames, boolean quoteTableName, final String attributePrefix) {
    final Set<String> normalizedFieldNames = getNormalizedColumnNames(rootNode, translateFieldNames);
    for (final String requiredColName : schema.getRequiredColumnNames()) {
        final String normalizedColName = normalizeColumnName(requiredColName, translateFieldNames);
        if (!normalizedFieldNames.contains(normalizedColName)) {
            String missingColMessage = "JSON does not have a value for the Required column '" + requiredColName + "'";
            if (failUnmappedColumns) {
                getLogger().error(missingColMessage);
                throw new ProcessException(missingColMessage);
            } else if (warningUnmappedColumns) {
                getLogger().warn(missingColMessage);
            }
        }
    }

    final StringBuilder sqlBuilder = new StringBuilder();
    int fieldCount = 0;
    sqlBuilder.append("DELETE FROM ");
    if (quoteTableName) {
        sqlBuilder.append(schema.getQuotedIdentifierString())
                .append(tableName)
                .append(schema.getQuotedIdentifierString());
    } else {
        sqlBuilder.append(tableName);
    }

    sqlBuilder.append(" WHERE ");

    // iterate over all of the elements in the JSON, building the SQL statement by adding the column names, as well as
    // adding the column value to a "<sql>.args.N.value" attribute and the type of a "<sql>.args.N.type" attribute add the
    // columns that we are inserting into
    final Iterator<String> fieldNames = rootNode.getFieldNames();
    while (fieldNames.hasNext()) {
        final String fieldName = fieldNames.next();

        final ColumnDescription desc = schema.getColumns().get(normalizeColumnName(fieldName, translateFieldNames));
        if (desc == null && !ignoreUnmappedFields) {
            throw new ProcessException("Cannot map JSON field '" + fieldName + "' to any column in the database");
        }

        if (desc != null) {
            if (fieldCount++ > 0) {
                sqlBuilder.append(" AND ");
            }

            if (escapeColumnNames) {
                sqlBuilder.append(schema.getQuotedIdentifierString())
                        .append(desc.getColumnName())
                        .append(schema.getQuotedIdentifierString());
            } else {
                sqlBuilder.append(desc.getColumnName());
            }
            sqlBuilder.append(" = ?");

            final int sqlType = desc.getDataType();
            attributes.put(attributePrefix + ".args." + fieldCount + ".type", String.valueOf(sqlType));

            final Integer colSize = desc.getColumnSize();
            final JsonNode fieldNode = rootNode.get(fieldName);
            if (!fieldNode.isNull()) {
                String fieldValue = fieldNode.asText();
                if (colSize != null && fieldValue.length() > colSize) {
                    fieldValue = fieldValue.substring(0, colSize);
                }
                attributes.put(attributePrefix + ".args." + fieldCount + ".value", fieldValue);
            }
        }
    }

    if (fieldCount == 0) {
        throw new ProcessException("None of the fields in the JSON map to the columns defined by the " + tableName + " table");
    }

    return sqlBuilder.toString();
}