Example usage for com.fasterxml.jackson.databind.node TreeTraversingParser TreeTraversingParser

List of usage examples for com.fasterxml.jackson.databind.node TreeTraversingParser TreeTraversingParser

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.node TreeTraversingParser TreeTraversingParser.

Prototype

public TreeTraversingParser(JsonNode n) 

Source Link

Usage

From source file:can.yrt.oba.serialization.JacksonSerializer.java

private static JsonParser getJsonParser(Reader reader) throws IOException, JsonProcessingException {
    TreeTraversingParser parser = new TreeTraversingParser(mMapper.readTree(reader));
    parser.setCodec(mMapper);/* w  w  w .  j  av  a  2 s  . com*/
    return parser;
}

From source file:uk.co.flax.biosolr.ontology.config.loaders.YamlConfigurationLoader.java

@Override
public IndexerConfiguration loadConfiguration() throws IOException {
    FileReader reader = new FileReader(configFile);
    final JsonNode node = mapper.readTree(yamlFactory.createParser(reader));
    final IndexerConfiguration config = mapper.readValue(new TreeTraversingParser(node),
            IndexerConfiguration.class);

    // Close the file reader
    reader.close();/*from  ww  w.  java 2 s.c  o  m*/

    return config;
}

From source file:com.hpcloud.util.config.ConfigurationFactory.java

private T build(JsonNode node, String filename) throws IOException, ConfigurationException {
    T config = mapper.readValue(new TreeTraversingParser(node), configType);
    validate(filename, config);//from   ww w .  j av a2  s. com
    return config;
}

From source file:org.mayocat.shop.payment.paypal.adaptivepayments.PaypalAdaptivePaymentsGatewayFactory.java

@Override
public PaymentGateway createGateway() {
    File globalConfigurationFile = new File(filesSettings.getPermanentDirectory() + SLASH + PAYMENTS_DIRECTORY
            + SLASH + ID + SLASH + CONFIG_FILE_NAME);

    File tenantConfigurationFile = new File(filesSettings.getPermanentDirectory() + SLASH + TENANTS_DIRECTORY
            + SLASH + this.context.getTenant().getSlug() + SLASH + PAYMENTS_DIRECTORY + SLASH + ID + SLASH
            + TENANT_CONFIGURATION_FILENAME);

    InputStream inputStream = null;
    try {//  w w w  .  j a  v a2 s.  c o m
        inputStream = new FileInputStream(globalConfigurationFile);

        JsonNode node = mapper.readTree(tenantConfigurationFile);
        PaypalAdaptivePaymentsTenantConfiguration configuration = mapper
                .readValue(new TreeTraversingParser(node), PaypalAdaptivePaymentsTenantConfiguration.class);

        return new PaypalAdaptivePaymentsPaymentGateway(inputStream, configuration.getEmail());
    } catch (FileNotFoundException e) {
        logger.error("Failed to create Paypal Adaptive payment gateway : configuration file not found");
        return null;
    } catch (JsonProcessingException e) {
        logger.error("Failed to create Paypal Adaptive payment gateway : invalid configuration file");
        return null;
    } catch (IOException e) {
        logger.error("Failed to create Paypal Adaptive payment gateway : IO exception");
        return null;
    }
}

From source file:com.meltmedia.jackson.crypto.DecryptWithObjectMapperTest.java

@Test
public void shouldDecryptWithoutObjectCodec() throws IOException {
    WithEncrypted withEncrypted = new WithEncrypted().withStringValue("some secret");

    JsonNode node = mapper.convertValue(withEncrypted, JsonNode.class);

    WithEncrypted result = mapper.copy().readValue(new TreeTraversingParser(node), WithEncrypted.class);
}

From source file:org.mayocat.accounts.passwords.zxcvbn.ZxcvbnPasswordMeter.java

public PasswordStrength getStrength(String password) {
    if (!hasInitialized) {
        this.initialize();
    }//from  w w w. ja  v a2  s . co  m

    Context context = Context.enter();
    Scriptable scope = context.newObject(global);
    scope.setParentScope(global);
    StringWriter stringWriter = new StringWriter();

    scope.put("writer", scope, stringWriter);
    scope.put("password", scope, password);

    String inputsAsArrayString = '['
            + Joiner.on(",").join(FluentIterable.from(inputs).transform(new Function<String, String>() {
                public String apply(String input) {
                    return "'" + input + "'";
                }
            })) + ']';

    context.evaluateString(scope, "var dump = function(o) { return JSON.stringify(o) };", "dump.js", 1, null);
    context.evaluateString(scope, "var result = zxcvbn(password, " + inputsAsArrayString + ");"
            + "writer.write(JSON.stringify(result))", "eval-zxcvbn.js", 1, null);

    ObjectMapper mapper = new ObjectMapper();
    final JsonNode node;
    try {
        node = mapper.readTree(stringWriter.toString());
        PasswordStrength result = mapper.readValue(new TreeTraversingParser(node), PasswordStrength.class);
        return result;
    } catch (IOException e) {
        throw new RuntimeException("Failed to check password strength", e);
    }
}

From source file:org.mayocat.theme.internal.DefaultThemeManager.java

private Theme getTheme(String themeId, Optional<Tenant> tenant, List<Level> ignore) {
    Level level = Level.TENANT_DIRECTORY;
    JsonNode node;/*from ww w . j ava 2s. co  m*/

    Path themeDirectory = null;

    if (tenant.isPresent() && !ignore.contains(Level.TENANT_DIRECTORY)) {
        themeDirectory = getTenantThemeDirectory(tenant.get().getSlug(), themeId);
    }

    if ((themeDirectory == null || !themeDirectory.toFile().exists())
            && !ignore.contains(Level.THEME_DIRECTORY)) {
        level = Level.THEME_DIRECTORY;
        themeDirectory = getGlobalThemeDirectory(themeId);
    }

    if (themeDirectory == null || !themeDirectory.toFile().exists()) {
        Optional<Path> path = getClasspathThemePath(themeId);
        if (path.isPresent() && !ignore.contains(Level.CLASSPATH)) {
            try {
                node = mapper.readTree(Resources.getResource(path.get().resolve(THEME_YML).toString()));
                ThemeDefinition definition = mapper.readValue(new TreeTraversingParser(node),
                        ThemeDefinition.class);

                return new Theme(path.get(), definition, null, Theme.Type.CLASSPATH);
            } catch (JsonProcessingException e) {
                Theme theme = new Theme(path.get(), null, null, Theme.Type.CLASSPATH, false);
            } catch (IOException e) {
                // Surrender
                logger.error("Could not resolve theme", e);
                return null;
            }
        } else {
            // Here there is nothing more we can do ; surrender
            return null;
        }
    }

    if (themeDirectory == null || !themeDirectory.resolve("theme.yml").toFile().isFile()) {
        // Theme not found
        return null;
    }

    ThemeDefinition definition = null;
    Theme parent = null;
    boolean definitionValid = true;
    logger.debug("Theme directory resolved to [{}]", themeDirectory.toString());
    try {
        node = mapper.readTree(themeDirectory.resolve("theme.yml").toFile());
        definition = mapper.readValue(new TreeTraversingParser(node), ThemeDefinition.class);
    } catch (JsonProcessingException e) {
        definition = null;
        definitionValid = false;
        logger.warn("Trying to load invalid theme. Error: {}", e.getMessage());
    } catch (IOException e) {
        logger.error("I/O exception parsing theme", e);
        // theme.yml file not found -> theme might have a parent
        if (tenant.isPresent()) {
            parent = getTheme(themeId, Optional.<Tenant>absent(), Arrays.asList(level));
        }
    }

    Theme theme = new Theme(themeDirectory, definition, parent, Theme.Type.FILE_SYSTEM, definitionValid);
    if (!level.equals(Level.THEME_DIRECTORY)) {
        // The theme lives in the tenant directory
        theme.setTenantOwnTheme(true);
    }

    return theme;
}

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

private T build(JsonNode node, String path) throws IOException, ConfigurationException {
    replaceEnvironmentVariables(node);/*w w  w.  ja  va2 s  . c o  m*/

    for (Map.Entry<Object, Object> pref : System.getProperties().entrySet()) {
        final String prefName = (String) pref.getKey();
        if (prefName.startsWith(propertyPrefix)) {
            final String configName = prefName.substring(propertyPrefix.length());
            addOverride(node, configName, System.getProperty(prefName));
        }
    }

    try {
        final T config = mapper.readValue(new TreeTraversingParser(node), klass);
        validate(path, config);
        return config;
    } catch (UnrecognizedPropertyException e) {
        Collection<Object> knownProperties = e.getKnownPropertyIds();
        List<String> properties = new ArrayList<>(knownProperties.size());
        for (Object property : knownProperties) {
            properties.add(property.toString());
        }
        throw EnvironmentConfigurationParsingException.builder("Unrecognized field").setFieldPath(e.getPath())
                .setLocation(e.getLocation()).addSuggestions(properties).setSuggestionBase(e.getPropertyName())
                .setCause(e).build(path);
    } catch (InvalidFormatException e) {
        String sourceType = e.getValue().getClass().getSimpleName();
        String targetType = e.getTargetType().getSimpleName();
        throw EnvironmentConfigurationParsingException.builder("Incorrect type of value")
                .setDetail("is of type: " + sourceType + ", expected: " + targetType)
                .setLocation(e.getLocation()).setFieldPath(e.getPath()).setCause(e).build(path);
    } catch (JsonMappingException e) {
        throw EnvironmentConfigurationParsingException.builder("Failed to parse configuration")
                .setDetail(e.getMessage()).setFieldPath(e.getPath()).setLocation(e.getLocation()).setCause(e)
                .build(path);
    }
}

From source file:jp.classmethod.aws.brian.BrianClient.java

@Override
public Optional<BrianTrigger> describeTrigger(TriggerKey key)
        throws BrianClientException, BrianServerException {
    logger.debug("describe trigger: {}", key);
    HttpResponse httpResponse = null;/*from   www.  j  a  va 2 s.c  om*/
    try {
        String path = String.format("/triggers/%s/%s", key.getGroup(), key.getName());
        URI uri = new URI(scheme, null, hostname, port, path, null, null);
        HttpUriRequest httpRequest = RequestBuilder.get().setUri(uri).build();
        httpResponse = httpClientExecute(httpRequest);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        JsonNode tree = mapper.readTree(httpResponse.getEntity().getContent());
        if (statusCode == HttpStatus.SC_OK) {
            if (tree.path("cronExpression").isMissingNode() == false) {
                return Optional.of(mapper.readValue(new TreeTraversingParser(tree), BrianCronTrigger.class));
            } else if (tree.path("repeatCount").isMissingNode() == false) {
                return Optional.of(mapper.readValue(new TreeTraversingParser(tree), BrianSimpleTrigger.class));
            }
            // TODO deserialize
            throw new Error("unknown scheduleType");
        } else if (statusCode >= 500) {
            throw new BrianServerException("status = " + statusCode);
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return Optional.empty();
        } else if (statusCode >= 400) {
            throw new BrianClientException("status = " + statusCode);
        } else {
            throw new Error("status = " + statusCode);
        }
    } catch (JsonProcessingException e) {
        throw new BrianServerException(e);
    } catch (URISyntaxException e) {
        throw new IllegalStateException(e);
    } catch (IOException e) {
        throw new BrianServerException(e);
    } catch (IllegalStateException e) {
        throw new Error(e);
    } finally {
        if (httpResponse != null) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    }
}