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:lti.LaunchRequest.java

public static LaunchRequest fromJSON(String json) {
    ObjectMapper om = new ObjectMapper();
    LaunchRequest launchRequest = null;/*from www . jav  a  2 s .com*/
    try {
        launchRequest = om.readValue(json, LaunchRequest.class);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return launchRequest;
}

From source file:com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils.java

public static String printDetails(String details) {
    Throwable failure = null;/*from   ww  w  .  j  a  v  a  2s  .c  o m*/
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.enableDefaultTyping(DefaultTyping.NON_FINAL);

        failure = mapper.readValue(details, Throwable.class);
    } catch (Exception e) {
        // eat up any data converter exceptions
    }

    if (failure != null) {
        StringBuilder builder = new StringBuilder();

        // Also print callstack
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        failure.printStackTrace(pw);

        builder.append(sw.toString());

        details = builder.toString();
    }

    return details;
}

From source file:org.apache.streams.gnip.powertrack.GnipActivityFixer.java

public static Activity fix(Activity activity) throws Exception {
    ObjectMapper mapper = new ObjectMapper();

    String des = mapper.writeValueAsString(activity);
    JSONObject json = new JSONObject(des);

    HashMap<ArrayList<String>, JSONObject> nullContents = new HashMap<ArrayList<String>, JSONObject>();
    ArrayList<String> drilldownKeys = new ArrayList<String>();

    findNullContents(json, drilldownKeys, nullContents);

    for (Map.Entry<ArrayList<String>, JSONObject> entry : nullContents.entrySet()) {
        JSONObject frag = entry.getValue();
        editJson(json, entry.getKey(), frag.get(""));
    }//w  ww. j av  a 2 s . co m

    StringReader str = new StringReader(json.toString());
    Activity testAct = null;
    try {
        testAct = mapper.readValue(str, Activity.class);
    } catch (Exception e) {
        LOGGER.error("Exception creating activity.", e);
        LOGGER.error("JSON : {}" + json.toString());
    }

    return testAct;
}

From source file:org.hawkular.metrics.api.jaxrs.influx.write.validation.SupportedInfluxObjectTest.java

@Parameters(name = "supportedInfluxObject: {1}")
public static Iterable<Object[]> testSupportedObjects() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    URL resource = Resources.getResource("influx/write/supported-write-objects.list.json");
    return FluentIterable //
            .from(Resources.readLines(resource, Charset.forName("UTF-8"))) //
            // Filter out comment lines
            .filter(new Predicate<String>() {
                @Override/*  ww w .  j  a  v a2  s  .  co  m*/
                public boolean apply(String input) {
                    return !input.startsWith("//") && !input.trim().isEmpty();
                }
            }) //
            .transform(new Function<String, Object[]>() {
                @Override
                public Object[] apply(String input) {
                    try {
                        return new Object[] { mapper.readValue(input, InfluxObject[].class), input };
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
}

From source file:org.hawkular.metrics.api.jaxrs.influx.write.validation.UnsupportedInfluxObjectTest.java

@Parameters(name = "unsupportedInfluxObject: {1}")
public static Iterable<Object[]> testSupportedObjects() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    URL resource = Resources.getResource("influx/write/unsupported-write-objects.list.json");
    return FluentIterable //
            .from(Resources.readLines(resource, Charset.forName("UTF-8"))) //
            // Filter out comment lines
            .filter(new Predicate<String>() {
                @Override//from w ww  .jav  a2s  .  c  o  m
                public boolean apply(String input) {
                    return !input.startsWith("//") && !input.trim().isEmpty();
                }
            }) //
            .transform(new Function<String, Object[]>() {
                @Override
                public Object[] apply(String input) {
                    try {
                        return new Object[] { mapper.readValue(input, InfluxObject[].class), input };
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
}

From source file:de.fau.cs.inf2.tree.evaluation.Main.java

/**
 * Parses path/repositories and prints the total number of
 * edit script results.//from  w  w w .  j av a 2  s  .  c  o m
 */
private static void readEditScriptsAndPrint(File path) {
    File repositories = new File(path, "/repositories/");
    ObjectMapper mapper = TreeEvalIO.createJSONMapper();
    int sum = 0;
    for (final File repository : repositories.listFiles((f) -> f.isDirectory())) {
        for (final File commitOld : repository.listFiles((f) -> f.isDirectory())) {
            for (final File commitNew : commitOld.listFiles((f) -> f.isDirectory())) {
                for (final File changedFile : commitNew.listFiles((f) -> f.isDirectory())) {
                    int numberOfFiles = changedFile.listFiles((f) -> f.getName().endsWith(".json")).length;
                    for (final File resultFile : changedFile.listFiles((f) -> f.getName().endsWith(".json"))) {
                        try {
                            DiffSummary result = mapper.readValue(resultFile, DiffSummary.class);
                            if (numberOfFiles >= 23) { // only count file revision if all necessery tree differencing versions produced results
                                if (result != null && result.type == TreeMatcherTypeEnum.MTDIFF_GTAST) {
                                    if (result.deletes + result.inserts + result.updates + result.moves > 0) { // only count files with changes
                                        sum++;
                                    }
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    System.out.println("Edit script results found: " + sum);
}

From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java

public static <T> T jsonToObject(String json, Class<T> clazz) {
    try {//from  www .  j ava2s  .  c om
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper.readValue(json, clazz);
    } catch (Exception ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}

From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java

public static Object jsonByteArrayObject(byte[] json, Class clazz) {
    try {/*from ww w  .  j a  v  a2  s  . c om*/
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper.readValue(json, clazz);
    } catch (Exception ex) {
        logger.log(Level.SEVERE, ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}

From source file:com.sugaronrest.restapicalls.methodcalls.Authentication.java

/**
 * Login to SugarCRM via REST API call./* w ww  .  j  a  va 2  s  .com*/
 *
 *  @param loginRequest LoginRequest object.
 *  @return LoginResponse object.
 */
public static LoginResponse login(LoginRequest loginRequest) throws Exception {

    LoginResponse loginResponse = new LoginResponse();

    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        String passwordHash = new BigInteger(1, md5.digest(loginRequest.password.getBytes())).toString(16);

        Map<String, String> userCredentials = new LinkedHashMap<String, String>();
        userCredentials.put("user_name", loginRequest.username);
        userCredentials.put("password", passwordHash);

        Map<String, Object> auth = new LinkedHashMap<String, Object>();
        auth.put("user_auth", userCredentials);
        auth.put("application_name", "RestClient");

        ObjectMapper mapper = new ObjectMapper();
        String jsonAuthData = mapper.writeValueAsString(auth);

        Map<String, Object> request = new LinkedHashMap<String, Object>();
        request.put("method", "login");
        request.put("input_type", "json");
        request.put("response_type", "json");
        request.put("rest_data", auth);

        String jsonRequest = mapper.writeValueAsString(request);

        request.put("rest_data", jsonAuthData);

        HttpResponse response = Unirest.post(loginRequest.url).fields(request).asString();

        String jsonResponse = response.getBody().toString();
        loginResponse.setJsonRawRequest(jsonRequest);
        loginResponse.setJsonRawResponse(jsonResponse);

        Map<String, Object> responseObject = mapper.readValue(jsonResponse, Map.class);
        if (responseObject.containsKey("id")) {
            loginResponse.sessionId = (responseObject.get("id").toString());
            loginResponse.setStatusCode(response.getStatus());
            loginResponse.setError(null);
        } else {
            ErrorResponse errorResponse = mapper.readValue(jsonResponse, ErrorResponse.class);
            errorResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            loginResponse.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            loginResponse.setError(errorResponse);
        }
    } catch (Exception exception) {
        ErrorResponse errorResponse = ErrorResponse.format(exception, exception.getMessage());
        loginResponse.setError(errorResponse);
    }

    return loginResponse;
}

From source file:io.druid.indexer.IndexGeneratorJob.java

public static List<DataSegment> getPublishedSegments(HadoopDruidIndexerConfig config) {
    final Configuration conf = JobHelper.injectSystemProperties(new Configuration());
    final ObjectMapper jsonMapper = HadoopDruidIndexerConfig.jsonMapper;

    ImmutableList.Builder<DataSegment> publishedSegmentsBuilder = ImmutableList.builder();

    final Path descriptorInfoDir = config.makeDescriptorInfoDir();

    try {//ww w.  j av a 2  s  .  c  om
        FileSystem fs = descriptorInfoDir.getFileSystem(conf);

        for (FileStatus status : fs.listStatus(descriptorInfoDir)) {
            final DataSegment segment = jsonMapper.readValue(fs.open(status.getPath()), DataSegment.class);
            publishedSegmentsBuilder.add(segment);
            log.info("Adding segment %s to the list of published segments", segment.getIdentifier());
        }
    } catch (FileNotFoundException e) {
        log.error(
                "[%s] SegmentDescriptorInfo is not found usually when indexing process did not produce any segments meaning"
                        + " either there was no input data to process or all the input events were discarded due to some error",
                e.getMessage());
        Throwables.propagate(e);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    List<DataSegment> publishedSegments = publishedSegmentsBuilder.build();

    return publishedSegments;
}