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:org.apache.openaz.xacml.admin.util.RESTfulPAPEngine.java

/**
 * Send a request to the PAP Servlet and get the response.
 * /*from   ww  w . ja  v  a  2  s.c om*/
 * The content is either an InputStream to be copied to the Request OutputStream
 *    OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream.
 * 
 * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
 * 
 * @param method
 * @param content   - EITHER an InputStream OR an Object to be encoded in JSON
 * @param collectionTypeClass
 * @param responseContentClass
 * @param parameters
 * @return
 * @throws Exception
 */
private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass,
        String... parameters) throws PAPException {
    HttpURLConnection connection = null;
    try {
        String fullURL = papServletURLString;
        if (parameters != null && parameters.length > 0) {
            String queryString = "";
            for (String p : parameters) {
                queryString += "&" + p;
            }
            fullURL += "?" + queryString.substring(1);
        }

        // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
        if (method.equals("GET") && content instanceof PDP && responseContentClass == StdPDPStatus.class) {
            // Adjust the url and properties appropriately
            fullURL = ((PDP) content).getId() + "?type=Status";
            content = null;
        }

        URL url = new URL(fullURL);

        //
        // Open up the connection
        //
        connection = (HttpURLConnection) url.openConnection();
        //
        // Setup our method and headers
        //
        connection.setRequestMethod(method);
        //            connection.setRequestProperty("Accept", "text/x-java-properties");
        //               connection.setRequestProperty("Content-Type", "text/x-java-properties");
        connection.setUseCaches(false);
        //
        // Adding this in. It seems the HttpUrlConnection class does NOT
        // properly forward our headers for POST re-direction. It does so
        // for a GET re-direction.
        //
        // So we need to handle this ourselves.
        //
        connection.setInstanceFollowRedirects(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        if (content != null) {
            if (content instanceof InputStream) {
                try {
                    //
                    // Send our current policy configuration
                    //
                    try (OutputStream os = connection.getOutputStream()) {
                        int count = IOUtils.copy((InputStream) content, os);
                        if (logger.isDebugEnabled()) {
                            logger.debug("copied to output, bytes=" + count);
                        }
                    }
                } catch (Exception e) {
                    logger.error("Failed to write content in '" + method + "'", e);
                    throw e;
                }
            } else {
                // The content is an object to be encoded in JSON
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(connection.getOutputStream(), content);
            }
        }
        //
        // Do the connect
        //
        connection.connect();
        if (connection.getResponseCode() == 204) {
            logger.info("Success - no content.");
            return null;
        } else if (connection.getResponseCode() == 200) {
            logger.info("Success. We have a return object.");

            // get the response content into a String
            String json = null;
            // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
            java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream());
            scanner.useDelimiter("\\A");
            json = scanner.hasNext() ? scanner.next() : "";
            scanner.close();
            logger.info("JSON response from PAP: " + json);

            // convert Object sent as JSON into local object
            ObjectMapper mapper = new ObjectMapper();

            if (collectionTypeClass != null) {
                // collection of objects expected
                final CollectionType javaType = mapper.getTypeFactory()
                        .constructCollectionType(collectionTypeClass, responseContentClass);

                Object objectFromJSON = mapper.readValue(json, javaType);
                return objectFromJSON;
            } else {
                // single value object expected
                Object objectFromJSON = mapper.readValue(json, responseContentClass);
                return objectFromJSON;
            }

        } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
            // redirection
            String newURL = connection.getHeaderField("Location");
            if (newURL == null) {
                logger.error(
                        "No Location header to redirect to when response code=" + connection.getResponseCode());
                throw new IOException(
                        "No redirect Location header when response code=" + connection.getResponseCode());
            }
            int qIndex = newURL.indexOf("?");
            if (qIndex > 0) {
                newURL = newURL.substring(0, qIndex);
            }
            logger.info("Redirect seen.  Redirecting " + fullURL + " to " + newURL);
            return newURL;
        } else {
            logger.warn("Unexpected response code: " + connection.getResponseCode() + "  message: "
                    + connection.getResponseMessage());
            throw new IOException("Server Response: " + connection.getResponseCode() + ": "
                    + connection.getResponseMessage());
        }

    } catch (Exception e) {
        logger.error("HTTP Request/Response to PAP: " + e, e);
        throw new PAPException("Request/Response threw :" + e);
    } finally {
        // cleanup the connection
        if (connection != null) {
            try {
                // For some reason trying to get the inputStream from the connection
                // throws an exception rather than returning null when the InputStream does not exist.
                InputStream is = null;
                try {
                    is = connection.getInputStream();
                } catch (Exception e1) { //NOPMD
                    // ignore this
                }
                if (is != null) {
                    is.close();
                }

            } catch (IOException ex) {
                logger.error("Failed to close connection: " + ex, ex);
            }
            connection.disconnect();
        }
    }
}

From source file:org.hawkular.client.ClientResponse.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public ClientResponse(Class<?> clazz, Response response, int statusCode, String tenantId,
        Class<? extends Collection> collectionType) {
    try {/* ww w  .j a v a  2 s .  c  om*/
        this.setStatusCode(response.getStatus());
        if (response.getStatus() == statusCode) {
            this.setSuccess(true);
            if (clazz.getName().equalsIgnoreCase(String.class.getName())) {
                this.setEntity((T) response.readEntity(clazz));
            } else if (clazz.getName().equalsIgnoreCase(Condition.class.getName())) {
                ObjectMapper objectMapper = new ObjectMapper();
                String jsonConditions = response.readEntity(String.class);
                JsonNode rootNode = objectMapper.readTree(jsonConditions);
                List<Condition> conditions = new ArrayList<>();
                if (!(null == jsonConditions || jsonConditions.trim().isEmpty())) {
                    for (JsonNode conditionNode : rootNode) {
                        Condition condition = JacksonDeserializer.deserializeCondition(conditionNode);
                        if (condition == null) {
                            this.setSuccess(false);
                            this.setErrorMsg("Bad json conditions: " + jsonConditions);
                            return;
                        }
                        conditions.add(condition);
                    }
                }
                this.setEntity((T) conditions);
            } else {
                ObjectMapper objectMapper = new ObjectMapper();
                InventoryJacksonConfig.configure(objectMapper);
                MetricsJacksonConfig.configure(objectMapper);
                if (clazz.getName().equalsIgnoreCase(Tenant.class.getName())) {
                    objectMapper.addMixIn(CanonicalPath.class, CanonicalPathMixin.class);
                } else if (tenantId != null) {
                    DetypedPathDeserializer
                            .setCurrentCanonicalOrigin(CanonicalPath.of().tenant(tenantId).get());
                }
                if (collectionType != null) {
                    this.setEntity(objectMapper.readValue(response.readEntity(String.class),
                            objectMapper.getTypeFactory().constructCollectionType(collectionType, clazz)));
                } else {
                    this.setEntity((T) objectMapper.readValue(response.readEntity(String.class), clazz));
                }
            }
        } else {
            this.setErrorMsg(response.readEntity(String.class));
        }
    } catch (JsonParseException e) {
        _logger.error("Error, ", e);
    } catch (JsonMappingException e) {
        _logger.error("Error, ", e);
    } catch (IOException e) {
        _logger.error("Error, ", e);
    } finally {
        response.close();
        if (_logger.isDebugEnabled()) {
            _logger.debug("Client response:{}", this.toString());
        }
    }
}

From source file:org.broadleafcommerce.openadmin.web.rulebuilder.DataDTODeserializer.java

@Override
public DataDTO deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    ObjectNode root = (ObjectNode) mapper.readTree(jp);
    Iterator<Map.Entry<String, JsonNode>> elementsIterator = root.fields();
    DataDTO dataDTO = new DataDTO();
    ExpressionDTO expressionDTO = new ExpressionDTO();
    boolean isExpression = false;
    while (elementsIterator.hasNext()) {
        Map.Entry<String, JsonNode> element = elementsIterator.next();
        String name = element.getKey();
        if ("id".equals(name)) {
            expressionDTO.setId(getNullAwareText(element.getValue()));
            isExpression = true;/*from   w  w w.  java2 s.c  o  m*/
        }

        if ("operator".equals(name)) {
            expressionDTO.setOperator(getNullAwareText(element.getValue()));
            isExpression = true;
        }

        if ("value".equals(name)) {
            expressionDTO.setValue(getNullAwareText(element.getValue()));
            isExpression = true;
        }

        if ("pk".equals(name)) {
            if (getNullAwareText(element.getValue()) == null
                    || StringUtils.isBlank(element.getValue().asText())) {
                dataDTO.setPk(null);
            } else {
                dataDTO.setPk(element.getValue().asLong());
            }
        }
        if ("quantity".equals(name)) {
            if (getNullAwareText(element.getValue()) == null) {
                dataDTO.setQuantity(null);
            } else {
                dataDTO.setQuantity(element.getValue().asInt());
            }
        }

        if ("condition".equals(name)) {
            dataDTO.setCondition(getNullAwareText(element.getValue()));
        }

        if ("rules".equals(name)) {
            CollectionType dtoCollectionType = mapper.getTypeFactory().constructCollectionType(ArrayList.class,
                    DataDTO.class);
            dataDTO.setRules((ArrayList<DataDTO>) mapper.readValue(element.getValue().traverse(jp.getCodec()),
                    dtoCollectionType));
        }
    }

    if (isExpression) {
        return expressionDTO;
    } else {
        return dataDTO;
    }
}

From source file:capital.scalable.restdocs.jackson.FieldDocumentationGeneratorTest.java

@Test
public void testGenerateDocumentationForConstraints() throws Exception {
    // given//from   ww  w  . j  a v a2s . c  om
    ObjectMapper mapper = createMapper();

    JavadocReader javadocReader = mock(JavadocReader.class);

    ConstraintReader constraintReader = mock(ConstraintReader.class);
    when(constraintReader.isMandatory(NotNull.class)).thenReturn(true);
    when(constraintReader.isMandatory(NotEmpty.class)).thenReturn(true);
    when(constraintReader.isMandatory(NotBlank.class)).thenReturn(true);

    when(constraintReader.getConstraintMessages(ConstraintResolution.class, "location"))
            .thenReturn(singletonList("A constraint for location"));
    when(constraintReader.getConstraintMessages(ConstraintResolution.class, "type"))
            .thenReturn(singletonList("A constraint for type"));
    when(constraintReader.getOptionalMessages(ConstraintResolution.class, "type"))
            .thenReturn(singletonList("false"));
    when(constraintReader.getOptionalMessages(ConstraintResolution.class, "params"))
            .thenReturn(singletonList("false"));
    when(constraintReader.getConstraintMessages(ConstraintField.class, "value"))
            .thenReturn(asList("A constraint1 for value", "A constraint2 for value"));
    when(constraintReader.getOptionalMessages(ConstraintField.class, "value"))
            .thenReturn(singletonList("false"));

    FieldDocumentationGenerator generator = new FieldDocumentationGenerator(mapper.writer(), javadocReader,
            constraintReader);
    Type type = ConstraintResolution.class;

    // when
    List<ExtendedFieldDescriptor> fieldDescriptions = cast(
            generator.generateDocumentation(type, mapper.getTypeFactory()));

    // then
    assertThat(fieldDescriptions.size(), is(5));
    assertThat(fieldDescriptions.get(0),
            is(descriptor("location", "String", null, "true", "A constraint for location")));
    assertThat(fieldDescriptions.get(1),
            is(descriptor("type", "Integer", null, "false", "A constraint for type")));
    assertThat(fieldDescriptions.get(2), is(descriptor("params", "Array", null, "false")));
    assertThat(fieldDescriptions.get(3), is(descriptor("params[].value", "String", null, "false",
            "A constraint1 for value", "A constraint2 for value")));
    assertThat(fieldDescriptions.get(4), is(descriptor("flags", "Array", null, "true")));
}

From source file:com.dell.asm.asmcore.asmmanager.app.rest.DeploymentService.java

static ObjectMapper buildObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector ai = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(ai);
    return mapper;
}

From source file:windows.webservices.JsonDeserializer.Deserializer.java

@Override
public E deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
    try {// w ww. j a  v a2  s. c  o  m

        JsonNode json = jp.getCodec().readTree(jp);

        if (StringUtils.isEmpty(json.toString()) || json.toString().length() < 4) {
            return getNullValue(dc);
        }
        E instance = classChild.newInstance();
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule modul = new SimpleModule("parroquia")
                .addDeserializer(Parroquia.class, new ParroquiaDeserializer())
                .addDeserializer(Semana.class, new SemanaDeserializer())
                .addDeserializer(Animal.class, new AnimalDeserializer())
                .addDeserializer(Semana.class, new SemanaDeserializer())
                .addDeserializer(Especie.class, new EspecieDeserializer())
                .addDeserializer(Persona.class, new PersonaDeserializer())
                .addDeserializer(Permiso.class, new PermisoDeserializer())
                .addDeserializer(Usuario.class, new UsuarioDeserializer())
                .addDeserializer(Cliente.class, new ClienteDeserializer())
                .addDeserializer(Municipio.class, new MunicipioDeserializer())
                .addDeserializer(Animal_has_Caso.class, new Animal_has_CasoDeserializer())
                .addDeserializer(Caso.class, new CasoDeserializer())
                .addDeserializer(Novedades.class, new NovedadesDeserializer())
                .addDeserializer(RegistroVacunacion.class, new RegistroVacunacionDeserializer())
                .addDeserializer(RegistroVacunacion_has_Animal.class,
                        new RegistroVacunacion_has_AnimalDeserializer())
                .addDeserializer(Vacunacion.class, new VacunacionDeserializer());
        mapper.registerModule(modul);

        for (Field field : ReflectionUtils.getAllFields(classChild)) {
            Object value = null;
            Iterator<String> it = json.fieldNames();
            String column = null;
            String fieldName = field.getName();
            JsonProperty property = field.getAnnotation(JsonProperty.class);
            if (property != null) {
                fieldName = property.value();
            }
            while (it.hasNext()) {
                String name = it.next();
                if (Objects.equals(name.trim(), fieldName)) {
                    column = name;
                    break;
                }
            }
            if (column == null) {
                System.out.println("No se reconoce la siguente columna : " + fieldName + " de : "
                        + classChild.getSimpleName());
                continue;
            }
            if (field.getType().equals(String.class)) {
                value = json.get(column).asText();
            } else if (Collection.class.isAssignableFrom(field.getType())) {
                if (StringUtils.isNotEmpty(json.get(column).toString())) {
                    ParameterizedType stringListType = (ParameterizedType) field.getGenericType();
                    Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0];
                    value = mapper.readValue(json.get(column).toString(),
                            mapper.getTypeFactory().constructCollectionType(List.class, stringListClass));
                } else {
                    value = null;
                }
            } else if (!field.getType().equals(Date.class)) {
                try {
                    value = mapper.convertValue(json.get(column), field.getType());
                } catch (IllegalArgumentException ex) {
                    value = null;
                }
            } else {
                String date = json.get(column).textValue();
                try {
                    if (date != null) {
                        value = d.parse(date.replace("-", "/"));
                    }
                } catch (ParseException ex) {
                    Logger.getLogger(Deserializer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            ReflectionUtils.runSetter(field, instance, value);
        }
        return instance;
    } catch (InstantiationException | IllegalAccessException ex) {
        Logger.getLogger(Deserializer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return getNullValue(dc);
}

From source file:com.github.FraggedNoob.GitLabTransfer.GitlabRelatedData.java

/**
 * Reads all the data from JSON files except for the hostUrl, projectName,
 * and apiToken.//www  .  j  av  a2  s .c  o  m
 * @param filepath The filepath prefix
 * @return T=success, F=fail
 */
public boolean readAllData(String filepath) {

    ObjectMapper mapper = new ObjectMapper();

    File w;
    String wname = "(none)";

    w = createFileForReading(filepath, "_project");
    if (w == null) {
        return false;
    }

    // Project 
    try {
        this.project = mapper.readValue(w, GitlabProject.class);
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error reading project from %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Read project (%s) from %s.\n", this.project.getName(), wname);

    // Users
    w = createFileForReading(filepath, "_users");
    if (w == null) {
        return false;
    }
    try {
        this.users = mapper.readValue(w, new TypeReference<List<GitlabUser>>() {
        });
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error reading from users to %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Read %d users from %s.\n", this.users.size(), wname);

    // Milestones
    w = createFileForReading(filepath, "_milestones");
    if (w == null) {
        return false;
    }
    try {
        // Read in as a List first, matches output
        List<GitlabMilestone> ml = mapper.readValue(w, new TypeReference<List<GitlabMilestone>>() {
        });
        this.milestones.addAll(ml);
        // Read directly as Set:
        //this.milestones.clear();
        //JavaType type = mapper.getTypeFactory().constructCollectionType(Set.class, GitlabMilestone.class);
        //this.milestones = mapper.readValue(w,  type);
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error reading milestones from %s.\n", wname);
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        System.out.printf("Error reading milestones from %s - incorrect data.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Read %d milestones from %s.\n", this.milestones.size(), wname);

    // Issues
    w = createFileForReading(filepath, "_issues");
    if (w == null) {
        return false;
    }
    try {
        // Read in as a List first, matches output
        List<GitlabIssue> mi = mapper.readValue(w, new TypeReference<List<GitlabIssue>>() {
        });
        this.issues.addAll(mi);
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error writing to issues to %s.\n", wname);
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        System.out.printf("Error reading issues from %s - incorrect data.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Read %d issues to %s.\n", this.issues.size(), wname);

    // Issue Notes
    w = createFileForReading(filepath, "_inotes");
    if (w == null) {
        return false;
    }
    try {
        this.issueNotes.clear();
        // Read in as a Map of Integer vs. List<GitlabNote>
        JavaType valtype = mapper.getTypeFactory().constructCollectionType(List.class, GitlabNote.class);
        JavaType keytype = mapper.getTypeFactory().constructType(Integer.class);
        JavaType maptype = mapper.getTypeFactory().constructMapType(Map.class, keytype, valtype);
        Map<Integer, List<GitlabNote>> mapList = mapper.readValue(w, maptype);

        for (Integer k : mapList.keySet()) {
            SortedSet<GitlabNote> s = new TreeSet<GitlabNote>(new NoteOrderByID());
            s.addAll(mapList.get(k));
            issueNotes.put(k, s);
        }

        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error reading issue notes from %s.\n", wname);
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        System.out.printf("Error reading issues notes from %s - incorrect data.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Read %d sets of issue notes to %s.\n", issueNotes.size(), wname);

    System.out.printf("Reading from files complete.\n");

    return true;
}

From source file:com.dell.asm.asmcore.asmmanager.app.rest.ServiceTemplateService.java

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;
}