Example usage for com.fasterxml.jackson.databind ObjectMapper readValue

List of usage examples for com.fasterxml.jackson.databind ObjectMapper readValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper readValue.

Prototype

@SuppressWarnings("unchecked")
    public <T> T readValue(byte[] src, JavaType valueType)
            throws IOException, JsonParseException, JsonMappingException 

Source Link

Usage

From source file:org.basinmc.maven.plugins.minecraft.access.AccessTransformationMap.java

/**
 * Reads an access transformation map from a supplied path.
 *
 * @throws IOException when accessing the file fails.
 *///  w  ww  .j  ava 2s  .  co m
@Nonnull
public static AccessTransformationMap read(@Nonnull Path path) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    {
        SimpleModule module = new SimpleModule("Access Transformation Serialization");
        module.addDeserializer(Visibility.class, new VisibilityJsonDeserializer());
        mapper.registerModule(module);
    }

    try (FileInputStream inputStream = new FileInputStream(path.toFile())) {
        return mapper.readValue(inputStream, AccessTransformationMap.class);
    }
}

From source file:com.netsteadfast.greenstep.util.ApplicationSiteUtils.java

private static boolean checkTestConnection(String host, String contextPath, HttpServletRequest request) {
    boolean test = false;
    String basePath = request.getScheme() + "://" + host + "/" + contextPath;
    String urlStr = basePath + "/pages/system/testJsonResult.action";
    try {/*w w w.j  a v  a2s  .c o  m*/
        logger.info("checkTestConnection , url=" + urlStr);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(urlStr);
        HttpClientParams params = new HttpClientParams();
        params.setConnectionManagerTimeout(TEST_JSON_HTTP_TIMEOUT);
        client.setParams(params);
        client.executeMethod(method);
        byte[] responseBody = method.getResponseBody();
        if (null == responseBody) {
            test = false;
            return test;
        }
        String content = new String(responseBody, Constants.BASE_ENCODING);
        ObjectMapper mapper = new ObjectMapper();
        @SuppressWarnings("unchecked")
        Map<String, Object> dataMap = (Map<String, Object>) mapper.readValue(content, HashMap.class);
        if (YesNo.YES.equals(dataMap.get("success"))) {
            test = true;
        }
    } catch (JsonParseException e) {
        logger.error(e.getMessage().toString());
    } catch (JsonMappingException e) {
        logger.error(e.getMessage().toString());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (!test) {
            logger.warn("checkTestConnection : " + String.valueOf(test));
        } else {
            logger.info("checkTestConnection : " + String.valueOf(test));
        }
    }
    return test;
}

From source file:org.keycloak.test.TestsHelper.java

public static boolean importTestRealm(String username, String password, String realmJsonPath)
        throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    ClassLoader classLoader = TestsHelper.class.getClassLoader();
    InputStream stream = TestsHelper.class.getResourceAsStream(realmJsonPath);
    RealmRepresentation realmRepresentation = mapper.readValue(stream, RealmRepresentation.class);

    Keycloak keycloak = Keycloak.getInstance(keycloakBaseUrl, "master", username, password, "admin-cli");
    keycloak.realms().create(realmRepresentation);
    testRealm = realmRepresentation.getRealm();
    generateInitialAccessToken(keycloak);
    return true;/*from   ww  w. ja va2  s .c  o m*/

}

From source file:com.anavationllc.o2jb.ConfigurationApp.java

private static Map<String, String> parseAction(final String json) {
    LOG.info("parsing:  " + json);
    Map<String, String> rtnValue = new HashMap<>();
    ObjectMapper mapper = new ObjectMapper();

    try {// w  ww.  j a  va2s .  co  m
        rtnValue = mapper.readValue(json, new TypeReference<HashMap<String, String>>() {
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

    return rtnValue;
}

From source file:com.vaadin.integration.maven.wscdn.CvalChecker.java

static CvalInfo parseJson(String json) {
    if (json == null) {
        return null;
    }//from   w  w  w  . j  av a 2s. com

    ObjectMapper objectMapper = new ObjectMapper();
    try {
        CvalInfo readValue = objectMapper.readValue(json, CvalInfo.class);
        return readValue;
    } catch (Exception e) {
        Logger.getLogger(CvalChecker.class.getName()).log(Level.WARNING, "Parsing json message failed: {0}",
                json);
        throw new RuntimeException(e);
    }
}

From source file:com.dell.asm.asmcore.asmmanager.util.deployment.HostnameUtilTest.java

static Deployment loadEsxiDeployment() throws IOException {
    // Set up some mock component data
    // Get some deployment data
    URL uri = HostnameUtilTest.class.getClassLoader().getResource("esxi_deployment.json");
    assertNotNull("Failed to load esxi_deployment.json", uri);
    String json = IOUtils.toString(uri, Charsets.UTF_8);

    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector ai = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(ai);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper.readValue(json, Deployment.class);
}

From source file:com.ntsync.android.sync.shared.SyncUtils.java

/**
 * Get the last saved Sync Result for an account.
 * /*ww w.  j  a  v a  2 s .  c  om*/
 * @param accountManager
 * @param account
 * @return Sync Result or null if there was not saved Result.
 */
public static AccountSyncResult getSyncResult(AccountManager accountManager, Account account) {
    String syncState = accountManager.getUserData(account, SYNC_STATE);

    AccountSyncResult result = null;
    if (syncState != null) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            result = mapper.readValue(syncState, AccountSyncResult.class);
        } catch (IOException e) {
            LogHelper.logW(TAG,
                    "Could not parse AccountSyncResult for account: " + account + " Value:" + syncState, e);
        }
    }
    return result;
}

From source file:io.vertx.stack.model.Stack.java

/**
 * Reads a stack descriptor./*  w  w w .ja v  a2  s  .c o  m*/
 *
 * @param descriptor the descriptor, must be a valid YAML file.
 * @return the created stack
 */
public static Stack fromDescriptor(File descriptor) {
    ObjectMapper mapper = new ObjectMapper();
    mapper = mapper.enable(JsonParser.Feature.ALLOW_COMMENTS)
            .enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
            .enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
            .enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
    try {
        return mapper.readValue(descriptor, Stack.class);
    } catch (IOException e) {
        throw new IllegalArgumentException("Cannot load stack from " + descriptor.getAbsolutePath(), e);
    }
}

From source file:com.yahoo.druid.hadoop.DruidRecordReader.java

public static SegmentLoadSpec readSegmentJobSpec(Configuration config, ObjectMapper jsonMapper) {
    try {/*from ww w  . j av a2 s.  c  om*/
        //first see if schema json itself is present in the config
        String schema = config.get(DruidInputFormat.CONF_DRUID_SCHEMA);
        if (schema != null) {
            logger.info("druid schema  = " + schema);
            return jsonMapper.readValue(schema, SegmentLoadSpec.class);
        }

        //then see if schema file location is in the config
        String schemaFile = config.get(DruidInputFormat.CONF_DRUID_SCHEMA_FILE);
        if (schemaFile == null) {
            throw new IllegalStateException("couldn't find schema");
        }

        logger.info("druid schema file location = " + schemaFile);

        FileSystem fs = FileSystem.get(config);
        FSDataInputStream in = fs.open(new Path(schemaFile));
        return jsonMapper.readValue(in.getWrappedStream(), SegmentLoadSpec.class);
    } catch (IOException ex) {
        throw new RuntimeException("couldn't load segment load spec", ex);
    }
}

From source file:com.tomtom.speedtools.json.Json.java

@Nullable
private static <T> T fromMapper(@Nonnull final ObjectMapper mapper, @Nonnull final String json,
        @Nonnull final Class<T> type) {
    assert mapper != null;
    assert json != null;
    assert type != null;
    try {// w  w w .  j  ava 2s  .c  o  m
        final StringReader reader = new StringReader(json);
        return mapper.readValue(reader, type);
    } catch (final JsonMappingException e) {
        LOG.error("fromMapper: Cannot map JSON {} --> object, mapper={}, exception={}", json,
                mapper.getClass().getCanonicalName(), e.toString());
    } catch (final IOException e) {
        LOG.error("fromMapper: Cannot map JSON {} --> object, mapper={}, exception={}", json,
                mapper.getClass().getCanonicalName(), e.toString());
    }
    return null;
}