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:de.fionera.javamailer.gui.mainView.controllerMain.java

/**
 * Loads the Settings from the provided File
 *
 * @param file   The File where the {@link Settings} are saved
 * @param mapper The {@link ObjectMapper} Instance
 */// w w w  .  ja  va 2 s .c o  m
private static void loadSetup(viewMain viewMain, File file, ObjectMapper mapper) {

    MailSetup settings = new MailSetup();
    try {
        settings = mapper.readValue(file, MailSetup.class);
    } catch (IOException e) {
        e.printStackTrace();
    }

    viewMain.getEditMailPanel().setEditorText(settings.getMailString());

    viewMain.getSetMailSettingsPanel().getFieldSubject().setText(settings.getSubjectString());

}

From source file:io.fabric8.kubernetes.client.dsl.base.OperationSupport.java

protected static <T> T unmarshal(InputStream is, Class<T> type) throws KubernetesClientException {
    try (BufferedInputStream bis = new BufferedInputStream(is)) {
        bis.mark(-1);/*ww  w . j  a v  a  2 s.  co  m*/
        int intch;
        do {
            intch = bis.read();
        } while (intch > -1 && Character.isWhitespace(intch));
        bis.reset();

        ObjectMapper mapper = JSON_MAPPER;
        if (intch != '{') {
            mapper = YAML_MAPPER;
        }
        return mapper.readValue(bis, type);
    } catch (IOException e) {
        throw KubernetesClientException.launderThrowable(e);
    }
}

From source file:edu.illinois.ncsa.springdata.SpringData.java

/**
 * This will clone the given object and return a complete copy. This is
 * especially useful to eagerly load all the elements in a collection when
 * the object is fetched from hibernate. The transaction that was used to
 * fetch the original object will need to be open to fetch any additional
 * fields./*from  w ww.  jav  a 2s .  c o  m*/
 * 
 * @param object
 *            the object that needs to be cloned
 * @return the cloned object with all fields filled in
 * @throws IOException
 *             throws an IOException if the object could not be cloned.
 */
@SuppressWarnings("unchecked")
public static <T> T cloneObject(T object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mapper.writeValue(baos, object);

    return removeDuplicate((T) mapper.readValue(baos.toByteArray(), object.getClass()));
}

From source file:io.github.retz.mesosc.MesosHTTPFetcher.java

public static Optional<String> extractDirectory(InputStream stream, String frameworkId, String executorId,
        String containerId) throws IOException {
    // TODO: prepare corresponding object type instead of using java.util.Map
    // Search path: {frameworks|complated_frameworks}/{completed_executors|executors}[.container='containerId'].directory
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Map<String, Object>> map = mapper.readValue(stream, java.util.Map.class);
    List<Map<String, Object>> frameworks = new ArrayList<>();
    if (map.get("frameworks") != null) {
        frameworks.addAll((List) map.get("frameworks"));
    }/*from  ww  w .  ja  va2 s  .  c  o  m*/
    if (map.get("completed_frameworks") != null) {
        frameworks.addAll((List) map.get("completed_frameworks"));
    }

    // TODO: use json-path for cleaner and flexible code
    for (Map<String, Object> framework : frameworks) {
        List<Map<String, Object>> both = new ArrayList<>();
        List<Map<String, Object>> executors = (List) framework.get("executors");
        if (executors != null) {
            both.addAll(executors);
        }
        List<Map<String, Object>> completedExecutors = (List) framework.get("completed_executors");
        if (completedExecutors != null) {
            both.addAll(completedExecutors);
        }
        Optional<String> s = extractDirectoryFromExecutors(both, executorId, containerId);
        if (s.isPresent()) {
            return s;
        }
    }
    LOG.error("No matching directory at framework={}, executor={}, container={}", frameworkId, executorId,
            containerId);
    return Optional.empty();
}

From source file:com.threecrickets.jygments.grammar.Lexer.java

@SuppressWarnings("unchecked")
public static Lexer getByFullName(String fullName) throws ResolutionException {
    // Try cache/*ww  w .  j  a va  2 s . co m*/
    Lexer lexer = lexers.get(fullName);
    if (lexer != null)
        return lexer;

    try {
        return (Lexer) Jygments.class.getClassLoader().loadClass(fullName).newInstance();
    } catch (InstantiationException x) {
    } catch (IllegalAccessException x) {
    } catch (ClassNotFoundException x) {
    }

    InputStream stream = Jygments.class.getClassLoader()
            .getResourceAsStream(fullName.replace('.', '/') + ".json");
    if (stream != null) {
        try {
            String converted = Util.rejsonToJson(stream);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.getFactory().configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            Map<String, Object> json = objectMapper.readValue(converted, HashMap.class);
            Object className = json.get("class");
            if (className == null)
                className = "";

            lexer = getByName(className.toString());
            lexer.addJson(json);
            lexer.resolve();

            if (lexer != null) {
                // Cache it
                Lexer existing = lexers.putIfAbsent(fullName, lexer);
                if (existing != null)
                    lexer = existing;
            }

            return lexer;
        } catch (JsonParseException x) {
            throw new ResolutionException(x);
        } catch (JsonMappingException x) {
            throw new ResolutionException(x);
        } catch (IOException x) {
            throw new ResolutionException(x);
        }
    }

    return null;
}

From source file:controllers.Index.java

private static void readData(final BulkRequestBuilder bulkRequest, final BufferedReader br, final Client client,
        final String aIndex) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    String line;// ww  w  . j a  v  a  2s.c  o m
    int currentLine = 1;
    String organisationData = null;
    String[] idUriParts = null;
    String organisationId = null;

    // First line: index with id, second line: source
    while ((line = br.readLine()) != null) {
        JsonNode rootNode = mapper.readValue(line, JsonNode.class);
        if (currentLine % 2 != 0) {
            JsonNode index = rootNode.get("index");
            idUriParts = index.findValue("_id").asText().split("/");
            organisationId = idUriParts[idUriParts.length - 1].replace("#!", "");
        } else {
            organisationData = line;
            JsonNode libType = rootNode.get("type");
            if (libType == null || !libType.textValue().equals("Collection")) {
                bulkRequest.add(client
                        .prepareIndex(aIndex, Application.CONFIG.getString("index.es.type"), organisationId)
                        .setSource(organisationData));
            }
        }
        currentLine++;
    }
}

From source file:org.helm.notation2.Monomer.java

public static Monomer fromJSON(String json) {
    ObjectMapper mapper = new ObjectMapper();

    try {/*from   ww  w .j  a v  a  2 s .  co  m*/
        Monomer mon = mapper.readValue(json, Monomer.class);
        return mon;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.modelon.oslc.adapter.fmi.integration.FMUConnector.java

public static FMU loadSingleFMU(String fmuInterfaceCMDPath, String fmuPath, String unzipTempDir)
        throws IOException {
    File cmd = new File(fmuInterfaceCMDPath);
    File fmu = new File(fmuPath);
    File fmuTempDir = new File(unzipTempDir + File.separator + fmu.getName());
    fmuTempDir.mkdirs();/*from  w  ww .  j a v  a 2 s.  co m*/

    try {
        ProcessBuilder builder = new ProcessBuilder(cmd.getPath(), "read", fmu.getPath(), fmuTempDir.getPath());
        builder.redirectErrorStream(true);
        Process p = builder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        StringBuilder sbuilder = new StringBuilder();
        String aux = "";

        while ((aux = reader.readLine()) != null) {
            aux = aux.replaceAll("\\\\", "\\\\\\\\");
            aux += "\r\n";
            sbuilder.append(aux);
        }

        String json = sbuilder.toString();
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        FMU fmuObject = mapper.readValue(json, FMU.class);
        if (fmuObject.fmiVersion != null)
            return mapper.readValue(json, FMU.class);
        else
            return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:de.javagl.jgltf.model.io.GltfUtils.java

/**
 * Creates a deep copy of the given {@link GlTF}.<br>
 * <br>/*from   w ww. jav  a2 s.c om*/
 * Note: Some details about the copy are not specified. E.g. whether
 * values that are mapped to <code>null</code> are still contained
 * in the copy. The goal of this method is to create a copy that is,
 * as far as reasonably possible, "structurally equivalent" to the
 * given input.
 * 
 * @param gltf The input 
 * @return The copy
 * @throws GltfException If the copy can not be created
 */
static GlTF copy(GlTF gltf) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(Include.NON_NULL);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        objectMapper.writeValue(baos, gltf);
        return objectMapper.readValue(baos.toByteArray(), GlTF.class);
    } catch (IOException e) {
        throw new GltfException("Could not copy glTF", e);
    }
}

From source file:de.thingweb.desc.ThingDescriptionParser.java

public static Thing fromJavaMap(Object json) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readValue(json.toString(), JsonNode.class);

    try {//from  w ww .  ja  va2 s  .com
        return parse(root);
    } catch (Exception e) {
        return parseOld(root);
    }
}