private String enrichMarkdown ( String message , JsonNode entitiesNode , JsonNode mediaNode ) throws InvalidInputException { TreeMap < Integer , JsonNode > entities = new TreeMap <> ( ) ; TreeMap < Integer , JsonNode > media = new TreeMap <> ( ) ; if ( entitiesNode != null ) { validateEntities ( entitiesNode ) ; for ( JsonNode node : entitiesNode . findParents ( INDEX_START ) ) { entities . put ( node . get ( INDEX_START ) . intValue ( ) , node ) ; } } if ( mediaNode != null ) { validateMedia ( mediaNode ) ; for ( JsonNode node : mediaNode . findParents ( INDEX ) ) { media . put ( node . get ( INDEX ) . intValue ( ) , node . get ( TEXT ) ) ; } } // If entity indices are outside the message, pad the message to the necessary length int lastIndex = Math . max ( ( ! entities . isEmpty ( ) ) ? entities . lastKey ( ) : 0 , ( ! media . isEmpty ( ) ) ? media . lastKey ( ) : 0 ) ; if ( message . length ( ) <= lastIndex ) { message = StringUtils . rightPad ( message , lastIndex + 1 ) ; } StringBuilder output = new StringBuilder ( ) ; for ( int i = 0 ; i < message . length ( ) ; i ++ ) { char c = message . charAt ( i ) ; if ( entities . containsKey ( i ) ) { JsonNode entity = entities . get ( i ) ; String entityType = entity . get ( TYPE ) . asText ( ) . toUpperCase ( ) ; String id = entity . get ( ID ) . asText ( ) ; output . append ( ENTITY_DELIMITER ) ; output . append ( entityType ) . append ( FIELD_DELIMITER ) ; output . append ( id ) ; output . append ( ENTITY_DELIMITER ) ; // We explicitly check the entity indices above, but make double sure that we don't get into an infinite loop here int endIndex = entity . get ( INDEX_END ) . intValue ( ) - 1 ; i = Math . max ( endIndex , i ) ; } else if ( media . containsKey ( i ) ) { JsonNode table = media . get ( i ) ; output . append ( ENTITY_DELIMITER ) ; output . append ( TABLE ) . append ( FIELD_DELIMITER ) ; for ( JsonNode row : table ) { for ( JsonNode cell : row ) { String text = cell . asText ( ) ; output . append ( text ) . append ( RECORD_DELIMITER ) ; } output . append ( GROUP_DELIMITER ) ; } output . append ( ENTITY_DELIMITER ) ; output . append ( c ) ; } else { output . append ( c ) ; } } return output . toString ( ) ; }
Generate intermediate markup to delimit custom nodes representing entities for further processing by the Markdown parser .