Example usage for com.fasterxml.jackson.databind JsonNode asText

List of usage examples for com.fasterxml.jackson.databind JsonNode asText

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode asText.

Prototype

public abstract String asText();

Source Link

Usage

From source file:com.spankingrpgs.scarletmoon.loader.EventLoader.java

/**
 * Constructs a media object from a music file name, and stores it in the {@link MusicMap}.
 *
 * @param music  The music file to turn into media
 *
 * @return The name of the song that was just stored
 *///  ww w.  j ava 2s  .  com
private String hydrateMusic(JsonNode music) {
    if (music == null) {
        return null;
    }
    String musicName = music.asText();
    MusicMap musicMap = MusicMap.INSTANCE;
    if (musicMap.containsKey(musicName)) {
        return musicName;
    }
    //ogg is not supported
    List<String> types = Arrays.asList(".mp3", ".wav");
    Optional<String> musicFileName = types.stream()
            .map(type -> Paths.get(gameRoot, "data", "music", music.asText() + type)).map(Path::toString)
            .map(File::new).filter(File::exists).map(File::toURI).map(URI::toString).findFirst();

    if (!musicFileName.isPresent()) {
        LOG.warning(String.format("Music %s not found.", musicFileName));
        return musicName;
    }
    Media media = new Media(musicFileName.get());
    musicMap.put(musicName, media);
    return musicName;
}

From source file:com.spankingrpgs.scarletmoon.loader.EventLoader.java

/**
 * Given a node containing state modifying commands that need to be executed, constructs a Consumer
 * that applies all of those changes in sequence.
 *
 * @param commands  The commands to execute at the end of the event, if null then returns
 * {@link UniversalEvent#NO_CHANGES}//  w w  w .j ava 2s .  c o  m
 *
 * @return  The consumer that executes all of the commands when given a {@link GameState}
 */
private Consumer<TextResolver> hydrateCommands(JsonNode commands) {
    if (commands == null) {
        return UniversalEvent.NO_CHANGES;
    }

    List<Consumer<TextResolver>> hydratedCommands = new ArrayList<>();
    for (JsonNode command : commands) {
        Matcher matcher = Pattern.compile(TextParser.FUNCTION_REGEX).matcher(command.asText());
        if (!matcher.matches()) {
            String msg = String.format("%s is not a valid function expression.", command.asText());
            LOG.log(Level.SEVERE, msg);
            throw new IllegalArgumentException(msg);
        }
        String functionName = matcher.group(TextParser.FUNCTION_NAME_GROUP);
        List<String> functionArgs = Arrays.stream(matcher.group(TextParser.FUNCTION_ARGUMENTS_GROUP).split(","))
                .map(String::trim).collect(Collectors.toList());
        hydratedCommands.add(CollectionUtils.getValue(stateCommands, functionName).apply(functionArgs));
    }
    return gameState -> hydratedCommands.stream().forEach(command -> command.accept(gameState));
}

From source file:acromusashi.stream.example.bolt.JsonExtractBolt.java

/**
 * {@inheritDoc}/*from w  ww  .  j av a2 s.co m*/
 */
@Override
public void onExecute(StreamMessage message) {
    String jsonStr = message.getBody().toString();

    JsonNode rootJson;
    try {
        // JsonNode???
        rootJson = this.mapper.readTree(jsonStr);
    } catch (IOException ex) {
        String logFormat = "Recived message is not valid. Skip message. : Message={0}";
        logger.warn(MessageFormat.format(logFormat, jsonStr), ex);
        return;
    }

    // JsonNode?????
    JsonNode valueJson = rootJson.get(this.targetKey);
    if (valueJson == null) {
        String logFormat = "Target Value is not exist. : TargetKey={0}, Message={1}";
        logger.warn(MessageFormat.format(logFormat, this.targetKey, jsonStr));
        return;
    }

    StreamMessage sendMessage = new StreamMessage();
    sendMessage.setBody(valueJson.asText());
    emitWithOnlyAnchor(sendMessage);
}

From source file:de.thomaskrille.dropwizard.environment_configuration.EnvironmentConfigurationFactory.java

private String getReplacementForValue(final JsonNode node) {
    Matcher m = ENV_PATTERN.matcher(node.asText());
    if (!m.matches()) {
        return null;
    }/*from w  w  w.  j a v  a 2 s.  c om*/

    String environmentVariable = m.group(1);
    String defaultValue = m.group(3);

    String replacement = "";
    if (environmentProvider.getenv(environmentVariable) != null) {
        replacement = environmentProvider.getenv(environmentVariable);
    } else if (defaultValue != null) {
        replacement = defaultValue;
    }

    return replacement;
}

From source file:com.baasbox.commands.LinksResource.java

private String getAuthorOverride(JsonNode command) throws CommandParsingException {
    JsonNode node = command.get(ScriptCommand.PARAMS).get(AUTHOR);
    if (node != null && !node.isTextual()) {
        throw new CommandParsingException(command, "author must be a string");
    } else if (node != null) {
        return node.asText();
    }//from   w  ww.  j av  a 2s.c  o  m
    return null;
}

From source file:com.google.api.server.spi.request.ServletRequestParamReader.java

private Object getStandardParamValue(JsonNode body, String paramName) {
    if (!StandardParameters.isStandardParamName(paramName)) {
        throw new IllegalArgumentException("paramName");
    } else if (StandardParameters.USER_IP.equals(paramName)) {
        return servletRequest.getRemoteAddr();
    } else if (StandardParameters.PRETTY_PRINT.equals(paramName)) {
        return StandardParameters.shouldPrettyPrint(servletRequest);
    }/*from ww w .jav  a  2s.co m*/
    JsonNode value = body.get(paramName);
    if (value == null && StandardParameters.ALT.equals(paramName)) {
        return "json";
    }
    return value != null ? value.asText() : null;
}

From source file:com.epam.catgenome.manager.externaldb.ncbi.NCBIGeneManager.java

private void parseJsonFromPubmed(final JsonNode pubmedResultRoot, final JsonNode pubmedEntries,
        final NCBIGeneVO ncbiGeneVO) throws JsonProcessingException {
    if (pubmedResultRoot.isArray()) {
        ncbiGeneVO.setPubNumber(pubmedResultRoot.size());
        for (final JsonNode objNode : pubmedResultRoot) {
            if (ncbiGeneVO.getPubmedReferences().size() >= NUMBER_OF_PUBLICATIONS) {
                break;
            }/*ww  w  .  jav  a  2 s.com*/
            JsonNode jsonNode = pubmedEntries.path(RESULT_PATH).get("" + objNode.asText());
            NCBISummaryVO pubmedReference = mapper.treeToValue(jsonNode, NCBISummaryVO.class);
            pubmedReference.setLink(String.format(NCBI_PUBMED_URL, pubmedReference.getUid()));
            // take first author
            if (pubmedReference.getAuthors() != null) {
                pubmedReference.setMultipleAuthors(pubmedReference.getAuthors().size() > 1);
                NCBISummaryVO.NCBIAuthor ncbiAuthor = pubmedReference.getAuthors().get(0);
                pubmedReference.setAuthor(ncbiAuthor);
                pubmedReference.setAuthors(null);
            }

            ncbiGeneVO.getPubmedReferences().add(pubmedReference);
        }
    }
}

From source file:com.turn.shapeshifter.NamedSchemaSerializerTest.java

@Test
public void testLongAsString() throws Exception {
    NamedSchema schema = NamedSchema.of(Union.getDescriptor(), "Union").surfaceLongsAsStrings()
            .useSchema("union_value", "Union").useSchema("union_repeated", "Union");

    Union union = Union.newBuilder().setInt64Value(1234567890L).addInt64Repeated(1234567L).build();
    SchemaRegistry registry = new SchemaRegistry();
    registry.register(schema);//w w w  .  j av  a  2s . c om
    JsonNode result = schema.getSerializer().serialize(union, registry);
    Assert.assertTrue(result.isObject());
    Assert.assertEquals(JsonToken.VALUE_STRING, result.get("int64Value").asToken());
    Assert.assertEquals("1234567890", result.get("int64Value").asText());
    JsonNode arrayItem = result.get("int64Repeated").get(0);
    Assert.assertEquals(JsonToken.VALUE_STRING, arrayItem.asToken());
    Assert.assertEquals("1234567", arrayItem.asText());
}

From source file:org.illalabs.rss.RssStreamProviderTask.java

/**
 * Reads the url and queues the data//w w w . j  av  a  2s . c  o m
 * 
 * @param feedUrl
 *            rss feed url
 * @return set of all article urls that were read from the feed
 * @throws IOException
 *             when it cannot connect to the url or the url is malformed
 * @throws FeedException
 *             when it cannot reed the feed.
 */
@VisibleForTesting
protected Set<String> queueFeedEntries(URL feedUrl) throws IOException, FeedException {
    Set<String> batch = Sets.newConcurrentHashSet();
    URLConnection connection = feedUrl.openConnection();
    connection.setConnectTimeout(this.timeOut);
    connection.setConnectTimeout(this.timeOut);
    SyndFeedInput input = new SyndFeedInput();
    SyndFeed feed = input.build(new InputStreamReader(connection.getInputStream()));
    for (Object entryObj : feed.getEntries()) {
        SyndEntry entry = (SyndEntry) entryObj;
        ObjectNode nodeEntry = this.serializer.deserialize(entry);
        nodeEntry.put(RSS_KEY, this.feedDetails.getUrl());
        String entryId = determineId(nodeEntry);
        batch.add(entryId);
        Datum datum = new Datum(nodeEntry, entryId, DateTime.now());
        try {
            JsonNode published = nodeEntry.get(DATE_KEY);
            if (published != null) {
                try {
                    DateTime date = RFC3339Utils.parseToUTC(published.asText());
                    if (date.isAfter(this.publishedSince)
                            && (!seenBefore(entryId, this.feedDetails.getUrl()))) {
                        this.dataQueue.put(datum);
                        LOGGER.debug("Added entry, {}, to provider queue.", entryId);
                    }
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    LOGGER.trace(
                            "Failed to parse date from object node, attempting to add node to queue by default.");
                    if (!seenBefore(entryId, this.feedDetails.getUrl())) {
                        this.dataQueue.put(datum);
                        LOGGER.debug("Added entry, {}, to provider queue.", entryId);
                    }
                }
            } else {
                LOGGER.debug("No published date present, attempting to add node to queue by default.");
                if (!seenBefore(entryId, this.feedDetails.getUrl())) {
                    this.dataQueue.put(datum);
                    LOGGER.debug("Added entry, {}, to provider queue.", entryId);
                }
            }
        } catch (InterruptedException ie) {
            LOGGER.error("Interupted Exception.");
            Thread.currentThread().interrupt();
        }
    }
    return batch;
}

From source file:org.waarp.openr66.protocol.http.rest.handler.DbTaskRunnerR66RestMethodHandler.java

@Override
protected DbPreparedStatement getPreparedStatement(HttpRestHandler handler, RestArgument arguments,
        RestArgument result, Object body)
        throws HttpIncorrectRequestException, HttpInvalidAuthenticationException {
    ObjectNode arg = arguments.getUriArgs().deepCopy();
    arg.setAll(arguments.getBody());/*from  w w w.  j a  va2s.c  o  m*/
    int limit = arg.path(FILTER_ARGS.LIMIT.name()).asInt(0);
    boolean orderBySpecialId = arg.path(FILTER_ARGS.ORDERBYID.name()).asBoolean(false);
    JsonNode node = arg.path(FILTER_ARGS.STARTID.name());
    String startid = null;
    if (!node.isMissingNode()) {
        startid = node.asText();
    }
    if (startid == null || startid.isEmpty()) {
        startid = null;
    }
    node = arg.path(FILTER_ARGS.STOPID.name());
    String stopid = null;
    if (!node.isMissingNode()) {
        stopid = node.asText();
    }
    if (stopid == null || stopid.isEmpty()) {
        stopid = null;
    }
    String rule = arg.path(FILTER_ARGS.IDRULE.name()).asText();
    if (rule == null || rule.isEmpty()) {
        rule = null;
    }
    String req = arg.path(FILTER_ARGS.PARTNER.name()).asText();
    if (req == null || req.isEmpty()) {
        req = null;
    }
    String owner = arg.path(DbTaskRunner.Columns.OWNERREQ.name()).asText();
    if (owner == null || owner.isEmpty()) {
        owner = null;
    }
    boolean pending = arg.path(FILTER_ARGS.PENDING.name()).asBoolean(false);
    boolean transfer = arg.path(FILTER_ARGS.INTRANSFER.name()).asBoolean(false);
    boolean error = arg.path(FILTER_ARGS.INERROR.name()).asBoolean(false);
    boolean done = arg.path(FILTER_ARGS.DONE.name()).asBoolean(false);
    boolean all = arg.path(FILTER_ARGS.ALLSTATUS.name()).asBoolean(false);
    Timestamp start = null;
    node = arg.path(FILTER_ARGS.STARTTRANS.name());
    if (!node.isMissingNode()) {
        long val = node.asLong();
        if (val == 0) {
            DateTime received = DateTime.parse(node.asText());
            val = received.getMillis();
        }
        start = new Timestamp(val);
    }
    Timestamp stop = null;
    node = arg.path(FILTER_ARGS.STOPTRANS.name());
    if (!node.isMissingNode()) {
        long val = node.asLong();
        if (val == 0) {
            DateTime received = DateTime.parse(node.asText());
            val = received.getMillis();
        }
        stop = new Timestamp(val);
    }
    try {
        return DbTaskRunner.getFilterPrepareStatement(handler.getDbSession(), limit, orderBySpecialId, startid,
                stopid, start, stop, rule, req, pending, transfer, error, done, all, owner);
    } catch (WaarpDatabaseNoConnectionException e) {
        throw new HttpIncorrectRequestException("Issue while reading from database", e);
    } catch (WaarpDatabaseSqlException e) {
        throw new HttpIncorrectRequestException("Issue while reading from database", e);
    }
}