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

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

Introduction

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

Prototype

public TypeFactory getTypeFactory() 

Source Link

Document

Accessor for getting currently configured TypeFactory instance.

Usage

From source file:edu.usd.btl.toolTree.OntoToTree.java

public String jsonToJava(String input) throws Exception {
    try {/*  ww w .  j a va2s.co m*/
        //File input = new File("C:\\Users\\Tyler\\Documents\\GitHub\\BTL\\src\\ontology_files\\testEdam.json");

        /*
         CONVERT JSON TO JAVA OBJECTS
         */
        //map EDAM ontology JSON to List of objects
        ObjectMapper treeMapper = new ObjectMapper(); //create new Jackson Mapper
        ObjectWriter treeWriter = treeMapper.writer().withDefaultPrettyPrinter();
        List<EDAMNode> ontologyNodes = treeMapper.readValue(input,
                treeMapper.getTypeFactory().constructCollectionType(List.class, EDAMNode.class));
        System.out.println("********SIZE OF ontologyNodes*********" + ontologyNodes.size());
        for (EDAMNode node : ontologyNodes) { //for each ontology node
            System.out.println(node.getName());
            //build tree from ontology nodes

        }
        JsonNode rootNode = treeMapper.readValue(getOntoJson(), JsonNode.class);
        JsonNode tool = rootNode.get("name");

        System.out.println("\n\n\n\n****************************" + tool.toString());
        System.out.println("**** ONTOLOGY SIZE *****" + ontologyNodes.size());
        String jsonOutput = treeWriter.writeValueAsString(ontologyNodes.get(0));
        System.out.println("\n\n****ONTOLOGY JSON OUPUT*****+\n" + jsonOutput);

        //            IplantV1 iplantOutput = BETSConverter.toIplant(betsTool);
        //            String iplantOutputJson = iplantWriter.writeValueAsString(iplantOutput); //write Json as String
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
    return "jsonToJava success";
}

From source file:com.dell.asm.asmcore.asmmanager.client.util.ServiceTemplateClientUtil.java

private static ObjectMapper buildObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector ai = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(ai);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper;
}

From source file:com.netflix.genie.common.client.BaseGenieClient.java

/**
 * Execute a HTTP request.//from w w w  .  j  av  a2  s  .  c om
 *
 * @param <C>             The collection class if a collection is the expected response
 *                        entity.
 * @param request         The request to send. Not null.
 * @param collectionClass The collection class. Null if none expected.
 * @param entityClass     The entity class. Not null.
 * @return The response entity.
 * @throws GenieException On any error.
 */
public <C extends Collection> Object executeRequest(final HttpRequest request, final Class<C> collectionClass,
        final Class entityClass) throws GenieException {
    if (collectionClass == null && entityClass == null) {
        throw new GeniePreconditionException("No return type entered. Unable to continue.");
    }
    if (collectionClass != null && entityClass == null) {
        throw new GeniePreconditionException(
                "No entity class for collection class " + collectionClass + " entered.");
    }
    if (request == null) {
        throw new GeniePreconditionException("No request entered. Unable to continue..");
    }
    try (final HttpResponse response = this.client.executeWithLoadBalancer(request)) {
        if (response.isSuccess()) {
            LOGGER.debug("Response returned success.");
            final ObjectMapper mapper = new ObjectMapper();
            if (collectionClass != null) {
                final CollectionType type = mapper.getTypeFactory().constructCollectionType(collectionClass,
                        entityClass);
                return mapper.readValue(response.getInputStream(), type);
            } else {
                return mapper.readValue(response.getInputStream(), entityClass);
            }
        } else {
            throw new GenieException(response.getStatus(), response.getEntity(String.class));
        }
    } catch (final Exception e) {
        if (e instanceof GenieException) {
            throw (GenieException) e;
        } else {
            LOGGER.error(e.getMessage(), e);
            throw new GenieServerException(e);
        }
    }
}

From source file:org.wikimedia.analytics.kraken.schemas.JsonToClassConverter.java

/**
 * @param className refers to the name of the class that maps to the JSON file. Make sure that
 * all properties in the JSON file are defined in the Java class, else it will throw an error
 * @param file contains the name of the JSON file to be loaded. The default place to put this
 * file is in the src/main/resource folder
 * @param key name of the field from the JSON object that should be used as key to store the
 * JSON object in the HashMap. Suppose the field containing the key is called 'foo' then the
 * java Class should have a getter called getFoo.
 * @return/* w  w  w  .  j av  a2s .c  om*/
 * @throws JsonMappingException
 * @throws JsonParseException
 */
public final HashMap<String, Schema> construct(final String className, final String file, final String key)
        throws JsonMappingException, JsonParseException {
    JsonFactory jfactory = new JsonFactory();
    HashMap<String, Schema> map = new HashMap<String, Schema>();
    List<Schema> schemas = null;
    InputStream input;
    JavaType type;
    ObjectMapper mapper = new ObjectMapper();

    try {
        Schema schema = (Schema) Schema.class.getClassLoader().loadClass(className).newInstance();

        input = schema.getClass().getClassLoader().getResourceAsStream(file);

        type = mapper.getTypeFactory().constructCollectionType(List.class, schema.getClass());
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    try {
        JsonParser jParser = jfactory.createJsonParser(input);
        schemas = mapper.readValue(jParser, type);
    } catch (IOException e) {
        System.err.println("Specified file could not be found.");
    } finally {
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException e) {
            System.err.println("Could not close filestream");
        }
    }
    if (schemas != null) {
        for (Schema schemaInstance : schemas) {
            try {
                Method getKey = schemaInstance.getClass().getMethod(key);
                map.put(getKey.invoke(schemaInstance).toString(), schemaInstance);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                System.err.println("Specified key is not a valid Getter for " + className);
            }
        }
    }
    return map;
}

From source file:org.bonitasoft.engine.command.ExecuteBDMQueryCommandIT.java

private List<?> deserializeListResult(final byte[] result) throws Exception {
    final Class<?> loadClass = Thread.currentThread().getContextClassLoader()
            .loadClass(EMPLOYEE_QUALIF_CLASSNAME);
    final ObjectMapper mapper = new ObjectMapper();
    return (List<?>) mapper.readValue(result,
            mapper.getTypeFactory().constructCollectionType(List.class, loadClass));
}

From source file:com.proofpoint.http.client.SmileResponseHandler.java

@Override
public T handle(Request request, Response response) {
    if (!successfulResponseCodes.contains(response.getStatusCode())) {
        throw new UnexpectedResponseException(String.format("Expected response code to be %s, but was %d: %s",
                successfulResponseCodes, response.getStatusCode(), response.getStatusMessage()), request,
                response);//from   ww  w.  j a v a2s.  c o  m
    }
    String contentType = response.getHeader(CONTENT_TYPE);
    if (contentType == null) {
        throw new UnexpectedResponseException("Content-Type is not set for response", request, response);
    }
    if (!MediaType.parse(contentType).is(MEDIA_TYPE_SMILE)) {
        throw new UnexpectedResponseException(
                "Expected application/x-jackson-smile response from server but got " + contentType, request,
                response);
    }
    try {
        JsonParser jsonParser = new SmileFactory().createParser(response.getInputStream());
        ObjectMapper objectMapper = OBJECT_MAPPER_SUPPLIER.get();

        // Important: we are NOT to close the underlying stream after
        // mapping, so we need to instruct parser:
        jsonParser.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);

        return objectMapper.readValue(jsonParser,
                objectMapper.getTypeFactory().constructType(jsonCodec.getType()));
    } catch (InvalidFormatException e) {
        throw new IllegalArgumentException("Unable to create " + jsonCodec.getType() + " from SMILE response",
                e);
    } catch (IOException e) {
        throw new RuntimeException("Error reading SMILE response from server", e);
    }
}

From source file:com.omricat.yacc.backend.servlets.CurrenciesProcessor.java

CurrenciesProcessor(@NotNull final CurrencyService currencyService, @NotNull final NamesService namesService,
        @NotNull final ObjectMapper mapper, @NotNull final DataStore currenciesStore,
        @NotNull final DataStore namesStore) {

    this.namesService = checkNotNull(namesService);
    this.currenciesStore = checkNotNull(currenciesStore);
    this.namesStore = checkNotNull(namesStore);
    this.currencyService = checkNotNull(currencyService);
    this.mapper = checkNotNull(mapper);

    mapType = mapper.getTypeFactory().constructMapType(Map.class, String.class, String.class);

}

From source file:gt.dakaik.config.WebContext.java

public MappingJackson2HttpMessageConverter jacksonXmlMessageConverter() {
    MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();

    ObjectMapper mapper = new XmlMapper();

    //Registering Hibernate4Module to support lazy objects
    Hibernate4Module module = new Hibernate4Module();
    module.disable(Hibernate4Module.Feature.USE_TRANSIENT_ANNOTATION);
    mapper.registerModule(module);// w  ww. j  a v a  2 s  .c o m

    // Cambiar AnnotationIntrospector para usar anotaciones de JAXB
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(introspector);

    List<MediaType> MediaTypes = new ArrayList<>();
    MediaTypes.add(MediaType.APPLICATION_XML);
    messageConverter.setSupportedMediaTypes(MediaTypes);

    messageConverter.setObjectMapper(mapper);
    //log.debug("Listado de MediaTypes: [{}]", messageConverter.getSupportedMediaTypes().toString());

    return messageConverter;

}

From source file:org.forgerock.openam.examples.PwnedAuth.java

private boolean checkPwnedStatus() throws AuthLoginException {
    // Get service specific attribute configured in OpenAM
    String ssa = CollectionHelper.getMapAttr(options, "specificAttribute");

    // Get property from bundle
    String new_hdr = bundle.getString("pwnedauth-ui-login-header");
    substituteHeader(STATE_AUTH, new_hdr);

    String pwnedString = haveIBeenPwned();
    if (pwnedString == "") {
        return false;
    } else {/* w  ww.j av a  2  s.  co  m*/
        debug.message("PwnedAuth : result from service : " + pwnedString);

        // Parse JSON response into object map
        ObjectMapper mapper = new ObjectMapper();
        List<Map<String, Object>> userData = null;
        try {
            userData = mapper.readValue(pwnedString,
                    mapper.getTypeFactory().constructCollectionType(List.class, Map.class));
        } catch (IOException e) {
            debug.error("IOException " + e.getMessage());
        }
        ;

        // Construct JavaScript warning + Pwned table
        String p1 = "<div class=\"well\"><table class=\"table table-bordered table-striped\"><tbody><tr><th>Name</th><th>Breach date</th></tr>";
        for (int i = 0; i < userData.size(); i++) {
            p1 = p1 + "<tr><td>" + (String) userData.get(i).get("Title") + "</td><td>"
                    + (String) userData.get(i).get("BreachDate") + "</td></tr>";
        }
        String pwnedOutputScript = p1 + "</tbody></table></div>";

        String warningMsg = "Your email address (<strong>" + userMail
                + "</strong>) has been associated with an incident where data has been illegally accessed by hackers and then released publicly. Visit <strong><a href=\"https://haveibeenpwned.com\" target=\"_blank\">https://haveibeenpwned.com</a></strong> for a full description of the detected breach. Below is a summary of the breaches associated with your email address.";
        String clientScript = "$(document).ready(function(){" + "$('#loginButton_0').attr('value','Continue');"
                + "strUI='<div class=\"alert alert-danger\"><strong>Warning </strong>" + warningMsg + "</div>"
                + pwnedOutputScript + "';" + "$('#callback_0').prepend(strUI);" + "});";

        replaceCallback(STATE_AUTH, 0, new ScriptTextOutputCallback(clientScript));
        replaceCallback(STATE_AUTH, 1, new HiddenValueCallback("callback_1"));

        return true;
    }
}