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

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

Introduction

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

Prototype

public ObjectMapper configure(JsonGenerator.Feature f, boolean state) 

Source Link

Document

Method for changing state of an on/off JsonGenerator feature for JsonFactory instance this object mapper uses.

Usage

From source file:com.cleverCloud.cleverIdea.api.CcApi.java

@Nullable
public String wsLogSigner() {
    if (!isValidate() && !login())
        return null;

    OAuthRequest request = new OAuthRequest(Verb.GET, CleverCloudApi.BASE_URL);
    assert myService != null;
    myService.signRequest(myAccessToken, request);
    WebSocket ws = new WebSocket(
            request.getHeaders().toString().replace("{Authorization=", "").replace("}", ""));
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, false);
    StringWriter writer = new StringWriter();

    try {/*w  w  w . j  av a 2  s. c o  m*/
        mapper.writeValue(writer, ws);
        return writer.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:it.guru.nidi.atlassian.remote.jira.JiraRestServiceTest.java

@Test
@Ignore//from  w ww .j  a v a2  s.co  m
public void testExecuteImpl() throws Exception {
    JiraService service = TestUtils.jiraService();

    // final List allProjects = service.getAllProjects();

    RemotePriority[] priorities = service.getPriorities();
    RemoteIssue issue = service.getIssue("IPOM-23");
    final RemoteComment[] comments = service.getComments("IPOM-23");
    String s1 = service.fieldNameById("10040");
    String s = service.customFieldByName(issue, "Release Notes Comments");

    Object o = service.executeGet(
            "search?jql=" + URLEncoder.encode("id in linkedissues(IPOM-53) and (type=\"Test Case\")", "utf-8"));

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    List issues = (List) ((Map<String, Object>) o).get("issues");

    //      RemoteFieldValue[] desc = new RemoteFieldValue[]{new RemoteFieldValue("description", new String[]{issue.getDescription() + ""})};
    //       RemoteIssue issue = service.updateIssue(issue.getKey(), desc);

    RemoteIssue issue2 = new RemoteIssue();
    issue2.setSummary("summary");
    issue2.setProject("IPOM");
    JiraTasks tasks = new JiraTasks(service);
    issue2.setType(tasks.issueTypeByName("Task").getId());
    issue2.setStatus("Closed");
    issue2.setDescription("");
    issue2 = service.createIssue(issue2);

    RemoteAttachment attachment = service.getAttachmentsFromIssue("SIBAD-566")[0];
    InputStream in = service.loadAttachment(attachment);
    copy(in, new FileOutputStream(new File("target/" + attachment.getFilename())));

    List<IssueLinkType> issueLinkTypes = service.getIssueLinkTypes();
    service.linkIssues(new IssueLink("Blocking", "SIBAD-1103", "SIBAD-1104"));
    Object issueLinkType = service.executeGet("issueLinkType");
    Object user = service.executeGet("user?username=stni");
    System.out.println(issueLinkType);
}

From source file:org.jasig.cas.util.AbstractJacksonBackedJsonSerializer.java

/**
 * Initialize object mapper.//from   w  ww. j  a  va  2s  . c o m
 *
 * @return the object mapper
 */
protected ObjectMapper initializeObjectMapper() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    mapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC);
    mapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC);
    mapper.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.PROTECTED_AND_PUBLIC);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
    return mapper;
}

From source file:com.fpmislata.banco.presentacion.CreditoController.java

@RequestMapping(value = { "/Credito/{idCuentaBancaria}" }, method = RequestMethod.POST)
public void insert(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse,
        @PathVariable("idCuentaBancaria") int idCuentaBancaria, @RequestBody String json)
        throws JsonProcessingException {
    try {/*from  ww  w  .  j av a2 s.c  om*/
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        Credito credito = (Credito) objectMapper.readValue(json, Credito.class);

        CuentaBancaria cuentaBancaria = cuentaBancariaDAO.read(idCuentaBancaria);
        credito.setCuentaBancaria(cuentaBancaria);
        credito.setFecha(new Date());

        boolean ok = creditoDAO.comprobarCredito(credito.getCuentaBancaria().getUsuario());

        if (ok) {
            // ======================= Credito ============================= //

            creditoDAO.insert(credito);

            // ======================= Movimiento ============================= //
            MovimientoBancario movimientoBancario = new MovimientoBancario();

            movimientoBancario.setConcepto("Credito Bitbank");
            movimientoBancario.setFecha(new Date());
            movimientoBancario.setImporte(credito.getImporte());
            movimientoBancario.setTipoMovimientoBancario(TipoMovimientoBancario.Haber);
            movimientoBancario.setCuentaBancaria(credito.getCuentaBancaria());

            movimientoBancarioDAO.insert(movimientoBancario);
            noCache(httpServletResponse);
            httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            noCache(httpServletResponse);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
        }

    } catch (ConstraintViolationException cve) {
        List<BussinesMessage> errorList = new ArrayList();
        ObjectMapper jackson = new ObjectMapper();
        System.out.println("No se ha podido insertar la Cuenta Bancaria debido a los siguientes errores:");
        for (ConstraintViolation constraintViolation : cve.getConstraintViolations()) {
            String datos = constraintViolation.getPropertyPath().toString();
            String mensage = constraintViolation.getMessage();

            BussinesMessage bussinesMessage = new BussinesMessage(datos, mensage);
            errorList.add(bussinesMessage);
        }
        String jsonInsert = jackson.writeValueAsString(errorList);
        noCache(httpServletResponse);
        httpServletResponse.setStatus(httpServletResponse.SC_BAD_REQUEST);
    } catch (Exception ex) {
        noCache(httpServletResponse);
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            noCache(httpServletResponse);
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (Exception ex1) {
            noCache(httpServletResponse);
        }
    }
}

From source file:com.upnext.beaconos.sdk.backend.BeaconControlManagerImpl.java

private ObjectMapper getObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    return objectMapper;
}

From source file:graphql.servlet.GraphQLVariables.java

public GraphQLVariables(GraphQLSchema schema, String query, Map<String, Object> variables) {
    super();/*from   w  ww  .  ja  va  2  s.  c  o m*/
    this.schema = schema;
    this.query = query;
    ObjectMapper objectMapper = new ObjectMapper();
    // this will help combating issues with unknown fields like clientMutationId
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    new Parser().parseDocument(query).getDefinitions().stream().filter(d -> d instanceof OperationDefinition)
            .map(d -> (OperationDefinition) d).flatMap(d -> d.getVariableDefinitions().stream())
            .forEach(new Consumer<VariableDefinition>() {
                @SneakyThrows
                @Override
                public void accept(VariableDefinition d) {
                    GraphQLType type;
                    Type t = d.getType();
                    if (t instanceof TypeName) {
                        type = schema.getType(((TypeName) t).getName());
                    } else if (t instanceof NonNullType) {
                        accept(new VariableDefinition(d.getName(), ((NonNullType) t).getType()));
                        return;
                    } else {
                        type = null;
                    }
                    if (type instanceof GraphQLObjectBackedByClass) {
                        String value = objectMapper.writeValueAsString(variables.get(d.getName()));
                        Object val = objectMapper.readValue(value,
                                ((GraphQLObjectBackedByClass) type).getObjectClass());
                        GraphQLVariables.this.put(d.getName(), val);
                    } else {
                        GraphQLVariables.this.put(d.getName(), variables.get(d.getName()));
                    }
                }
            });
}

From source file:net.hydromatic.optiq.model.ModelHandler.java

public ModelHandler(OptiqConnection connection, String uri) throws IOException {
    super();/*from  ww w . j ava  2s  .c o  m*/
    this.connection = connection;
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    JsonRoot root;
    if (uri.startsWith("inline:")) {
        root = mapper.readValue(uri.substring("inline:".length()), JsonRoot.class);
    } else {
        root = mapper.readValue(new File(uri), JsonRoot.class);
    }
    visit(root);
}

From source file:com.jivesoftware.os.routing.bird.deployable.TenantRoutingBirdProviderBuilder.java

public ConnectionDescriptorsProvider build(OAuthSigner signer) {
    HttpClientConfig httpClientConfig = HttpClientConfig.newBuilder().build();
    final HttpClient httpClient = new HttpClientFactoryProvider()
            .createHttpClientFactory(Collections.singletonList(httpClientConfig), false)
            .createClient(signer, routesHost, routesPort);

    AtomicLong activeCount = new AtomicLong();
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    ConnectionDescriptorsProvider connectionsProvider = (connectionsRequest, expectedReleaseGroup) -> {
        activeCount.incrementAndGet();/* w  w  w .j  a  va 2 s  . co  m*/
        try {
            LOG.debug("Requesting connections:{}", connectionsRequest);

            String postEntity;
            try {
                postEntity = mapper.writeValueAsString(connectionsRequest);
            } catch (JsonProcessingException e) {
                LOG.error("Error serializing request parameters object to a string.  Object " + "was "
                        + connectionsRequest + " " + e.getMessage());
                return null;
            }

            HttpResponse response;
            try {
                response = httpClient.postJson(routesPath, postEntity, null);
            } catch (HttpClientException e) {
                LOG.error(
                        "Error posting query request to server.  The entity posted was {} and the endpoint posted to was {}",
                        new Object[] { postEntity, routesPath }, e);
                return null;
            }

            int statusCode = response.getStatusCode();
            if (statusCode >= 200 && statusCode < 300) {
                byte[] responseBody = response.getResponseBody();
                try {
                    ConnectionDescriptorsResponse connectionDescriptorsResponse = mapper.readValue(responseBody,
                            ConnectionDescriptorsResponse.class);
                    if (!connectionsRequest.getRequestUuid()
                            .equals(connectionDescriptorsResponse.getRequestUuid())) {
                        LOG.warn("Request UUIDs are misaligned, request:{} response:{}", connectionsRequest,
                                connectionDescriptorsResponse);
                    }
                    if (connectionDescriptorsResponse.getReturnCode() >= 0 && expectedReleaseGroup != null
                            && !expectedReleaseGroup.equals(connectionDescriptorsResponse.getReleaseGroup())) {
                        String responseEntity = new String(responseBody, StandardCharsets.UTF_8);
                        LOG.warn(
                                "Release group changed, active:{} request:{} requestEntity:{} responseEntity:{} response:{}",
                                activeCount.get(), connectionsRequest, postEntity, responseEntity,
                                connectionDescriptorsResponse);
                    }
                    LOG.debug("Request:{} ConnectionDescriptors:{}", connectionsRequest,
                            connectionDescriptorsResponse);
                    return connectionDescriptorsResponse;
                } catch (IOException x) {
                    LOG.error("Failed to deserialize response:" + new String(responseBody) + " "
                            + x.getMessage());
                    return null;
                }
            }
            return null;
        } finally {
            activeCount.decrementAndGet();
        }
    };
    return connectionsProvider;
}

From source file:org.mycontroller.standalone.api.jaxrs.mixins.McJacksonJson2Provider.java

@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
    ObjectMapper mapper = locateMapper(type, mediaType);

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    //AddMixIns// ww w.j  a  v a2s .c  om
    mapper.addMixIn(RuleDefinition.class, RuleDefinitionMixin.class);
    mapper.addMixIn(Dashboard.class, DashboardMixin.class);
    mapper.addMixIn(ExternalServer.class, ExternalServerMixin.class);
    mapper.addMixIn(ForwardPayload.class, ForwardPayloadMixin.class);
    mapper.addMixIn(Gateway.class, GatewayMixin.class);
    mapper.addMixIn(Node.class, NodeMixin.class);
    mapper.addMixIn(Operation.class, OperationMixin.class);
    mapper.addMixIn(Resource.class, ResourceMixin.class);
    mapper.addMixIn(ResourcesGroup.class, ResourcesGroupMixin.class);
    mapper.addMixIn(ResourcesGroupMap.class, ResourcesGroupMapMixin.class);
    mapper.addMixIn(Role.class, RoleMixin.class);
    mapper.addMixIn(Sensor.class, SensorMixin.class);
    mapper.addMixIn(Timer.class, TimerMixin.class);
    mapper.addMixIn(User.class, UserMixin.class);
    mapper.addMixIn(McScript.class, McScriptMixin.class);
    mapper.addMixIn(UidTag.class, UidTagMixin.class);
    mapper.addMixIn(McMessage.class, McMessageMixin.class);
    mapper.addMixIn(SensorVariableJson.class, SensorVariableJsonMixin.class);

    _logger.debug("Request: Headers:{}", httpHeaders);

    return super.readFrom(type, genericType, annotations, mediaType, httpHeaders, entityStream);
}

From source file:com.esri.geoportal.commons.ags.client.AgsClient.java

/**
 * Lists folder content.//from   ww w  .j  a v  a 2 s  .  c o m
 *
 * @param folder folder or <code>null</code>
 * @return content response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if accessing token fails
 */
public ContentResponse listContent(String folder) throws URISyntaxException, IOException {
    String url = rootUrl.toURI().resolve("rest/services/").resolve(StringUtils.stripToEmpty(folder))
            .toASCIIString();
    HttpGet get = new HttpGet(url + String.format("?f=%s", "json"));

    try (CloseableHttpResponse httpResponse = httpClient.execute(get);
            InputStream contentStream = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }
        String responseContent = IOUtils.toString(contentStream, "UTF-8");
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        ContentResponse response = mapper.readValue(responseContent, ContentResponse.class);
        response.url = url;
        return response;
    }
}