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:org.wso2.emm.agent.services.operation.OperationProcessor.java

/**
 * Set policy bundle.//from w ww . j  a v  a 2 s  . c  o m
 *
 * @param operation - Operation object.
 */
public void setPolicyBundle(org.wso2.emm.agent.beans.Operation operation) throws AndroidAgentException {
    if (isDeviceAdminActive()) {
        if (Preference.getString(context, Constants.PreferenceFlag.APPLIED_POLICY) != null) {
            operationManager.revokePolicy(operation);
        }
        String payload = operation.getPayLoad().toString();
        if (Constants.DEBUG_MODE_ENABLED) {
            Log.d(TAG, "Policy payload: " + payload);
        }
        PolicyOperationsMapper operationsMapper = new PolicyOperationsMapper();
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        try {
            if (payload != null) {
                Preference.putString(context, Constants.PreferenceFlag.APPLIED_POLICY, payload);
            }

            List<Operation> operations = mapper.readValue(payload, mapper.getTypeFactory()
                    .constructCollectionType(List.class, org.wso2.emm.agent.beans.Operation.class));

            for (org.wso2.emm.agent.beans.Operation op : operations) {
                op = operationsMapper.getOperation(op);
                this.doTask(op);
            }
            operation.setStatus(context.getResources().getString(R.string.operation_value_completed));
            operationManager.setPolicyBundle(operation);

            if (Constants.DEBUG_MODE_ENABLED) {
                Log.d(TAG, "Policy applied");
            }
        } catch (IOException e) {
            operation.setStatus(context.getResources().getString(R.string.operation_value_error));
            operation.setOperationResponse("Error occurred while parsing policy bundle stream.");
            operationManager.setPolicyBundle(operation);
            throw new AndroidAgentException("Error occurred while parsing stream", e);
        }
    } else {
        operation.setStatus(context.getResources().getString(R.string.operation_value_error));
        operation.setOperationResponse("Device administrator is not activated, hence cannot execute policies.");
        operationManager.setPolicyBundle(operation);
        throw new AndroidAgentException("Device administrator is not activated, hence cannot execute policies");
    }
}

From source file:com.pymegest.applicationserver.api.UsuarioController.java

@RequestMapping(value = { "/Usuario/{id_usuario}" }, method = RequestMethod.PUT)
public void update(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("id_usuario") int id_usuario, @RequestBody String jsonInput) {

    try {//from   w w w.java 2s .  c o m

        Usuario usuarioRead = usuarioDAO.read(id_usuario);

        if (usuarioRead != null) {

            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            Usuario usuario = (Usuario) objectMapper.readValue(jsonInput, Usuario.class);

            usuarioRead.setTipo_cuenta(usuario.getTipo_cuenta());

            usuarioDAO.update(usuarioRead);

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            String jsonOutput = objectMapper.writeValueAsString(usuario);
            response.getWriter().println(jsonOutput);

        }

        else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("No se ha encontrado ningun usuario para actualizar.");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }
}

From source file:org.opendaylight.groupbasedpolicy.jsonrpc.JsonRpcEndpointTest.java

@Before
public void setUp() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    /*/*ww w. jav a2s  . com*/
     * Create the message map, populating with just our test message
     */
    messageMap = new RpcMessageMap();
    JsonRpcEndpointTest.OpflexTest rpcMethod = new JsonRpcEndpointTest.OpflexTest();
    rpcMethod.setName(TEST_JSON_CLASS_NAME);
    messageMap.add(rpcMethod);

    decoder = new JsonRpcDecoder(1000);
    JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(null);
    channel = new EmbeddedChannel(decoder, binderHandler);

    endpoint = new JsonRpcEndpoint(channel.localAddress().toString(), null, objectMapper, channel, messageMap,
            this);
    binderHandler.setEndpoint(endpoint);
}

From source file:com.arpnetworking.jackson.ObjectMapperFactoryTest.java

@Test
public void testNewInstance() {
    final ObjectMapper objectMapper1 = ObjectMapperFactory.createInstance();
    final ObjectMapper objectMapper2 = ObjectMapperFactory.createInstance();
    Assert.assertNotSame(objectMapper1, objectMapper2);

    // Deserialization feature
    objectMapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
    objectMapper2.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Assert.assertTrue(objectMapper1.getDeserializationConfig()
            .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
    Assert.assertFalse(objectMapper2.getDeserializationConfig()
            .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));

    // Serialization feature
    objectMapper1.configure(SerializationFeature.INDENT_OUTPUT, true);
    objectMapper2.configure(SerializationFeature.INDENT_OUTPUT, false);
    Assert.assertTrue(objectMapper1.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT));
    Assert.assertFalse(objectMapper2.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT));
}

From source file:org.opendaylight.groupbasedpolicy.renderer.opflex.lib.OpflexConnectionServiceTest.java

@Test
public void testPublishSubscribeCallback() throws Exception {

    List<Role> testRoles = new ArrayList<Role>();
    testRoles.add(Role.POLICY_REPOSITORY);
    testRoles.add(Role.ENDPOINT_REGISTRY);
    testRoles.add(Role.OBSERVER);

    /*/*  w w w. j a va  2s.  c  o m*/
     * This is *far* from UT, but worthwhile for now
     */
    opflexService = new OpflexConnectionService(mockDataBroker, executor);

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    decoder = new JsonRpcDecoder(1000);
    JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(null);
    EmbeddedChannel channel = new EmbeddedChannel(decoder, binderHandler);

    RpcMessageMap messageMap = new RpcMessageMap();
    messageMap.addList(Role.DISCOVERY.getMessages());

    JsonRpcEndpoint ep = new JsonRpcEndpoint(IDENTITY, opflexService, objectMapper, channel, messageMap,
            opflexService);
    ep.setContext(mockOpflexServer);
    binderHandler.setEndpoint(ep);

    when(mockOpflexServer.getRoles()).thenReturn(testRoles);
    when(mockOpflexServer.getDomain()).thenReturn(OpflexConnectionService.OPFLEX_DOMAIN);
    opflexService.addConnection(ep);
    channel.writeInbound(copiedBuffer(opflexIdentityRequest, CharsetUtil.UTF_8));
    Object result = channel.readOutbound();
    result = channel.readOutbound();
    assertTrue(result != null);
    IdentityResponse resp = objectMapper.readValue(result.toString(), IdentityResponse.class);
    assertTrue(resp != null);
    assertTrue(resp.getResult().getMy_role().contains(Role.ENDPOINT_REGISTRY.toString()));
    assertTrue(resp.getResult().getMy_role().contains(Role.POLICY_REPOSITORY.toString()));
    assertTrue(resp.getResult().getMy_role().contains(Role.OBSERVER.toString()));
}

From source file:org.opendaylight.groupbasedpolicy.renderer.opflex.OpflexConnectionServiceTest.java

@Test
public void testPublishSubscribeCallback() throws Exception {

    List<Role> testRoles = new ArrayList<Role>();
    testRoles.add(Role.POLICY_REPOSITORY);
    testRoles.add(Role.ENDPOINT_REGISTRY);
    testRoles.add(Role.OBSERVER);

    /*//  w  w w. jav a2s  .  c o  m
     * This is *far* from UT, but worthwhile for now
     */
    opflexService = new OpflexConnectionService();
    opflexService.setDataProvider(mockDataBroker);
    List<RpcMessage> messages = Role.POLICY_REPOSITORY.getMessages();
    for (RpcMessage msg : messages) {
        opflexService.subscribe(msg, this);
    }

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    decoder = new JsonRpcDecoder(1000);
    JsonRpcServiceBinderHandler binderHandler = new JsonRpcServiceBinderHandler(null);
    EmbeddedChannel channel = new EmbeddedChannel(decoder, binderHandler);

    RpcMessageMap messageMap = new RpcMessageMap();
    messageMap.addList(Role.POLICY_REPOSITORY.getMessages());

    JsonRpcEndpoint ep = new JsonRpcEndpoint(IDENTITY, opflexService, objectMapper, channel, messageMap,
            opflexService);
    ep.setContext(mockOpflexServer);
    binderHandler.setEndpoint(ep);

    when(mockOpflexServer.getRoles()).thenReturn(testRoles);
    when(mockOpflexServer.getDomain()).thenReturn(OpflexConnectionService.OPFLEX_DOMAIN);
    opflexService.addConnection(ep);
    channel.writeInbound(copiedBuffer(opflexIdentityRequest, CharsetUtil.UTF_8));
    Object result = channel.readOutbound();
    result = channel.readOutbound();
    assertTrue(result != null);
    IdentityResponse resp = objectMapper.readValue(result.toString(), IdentityResponse.class);
    assertTrue(resp != null);
    assertTrue(resp.getResult().getMy_role().contains(Role.ENDPOINT_REGISTRY.toString()));
    assertTrue(resp.getResult().getMy_role().contains(Role.POLICY_REPOSITORY.toString()));
    assertTrue(resp.getResult().getMy_role().contains(Role.OBSERVER.toString()));
}

From source file:alluxio.client.rest.TestCase.java

/**
 * Runs the test case and returns the {@link HttpURLConnection}.
 */// w  w w .  jav a  2s  .  co  m
public HttpURLConnection execute() throws Exception {
    HttpURLConnection connection = (HttpURLConnection) createURL().openConnection();
    connection.setRequestMethod(mMethod);
    if (mOptions.getMD5() != null) {
        connection.setRequestProperty("Content-MD5", mOptions.getMD5());
    }
    if (mOptions.getInputStream() != null) {
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/octet-stream");
        ByteStreams.copy(mOptions.getInputStream(), connection.getOutputStream());
    }
    if (mOptions.getBody() != null) {
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", mOptions.getContentType());
        ObjectMapper mapper = new ObjectMapper();
        // make sure that serialization of empty objects does not fail
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        OutputStream os = connection.getOutputStream();
        os.write(mapper.writeValueAsString(mOptions.getBody()).getBytes());
        os.close();
    }

    connection.connect();
    if (Response.Status.Family.familyOf(connection.getResponseCode()) != Response.Status.Family.SUCCESSFUL) {
        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            Assert.fail("Request failed: " + IOUtils.toString(errorStream));
        }
        Assert.fail("Request failed with status code " + connection.getResponseCode());
    }
    return connection;
}

From source file:jp.classmethod.aws.brian.utils.BrianServerObjectMapperFactoryBean.java

@Override
protected ObjectMapper createInstance() {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule brianModule = new SimpleModule("brianServerModule", VERSION);
    brianModule.addSerializer(Trigger.class, new TriggerSerializer());
    mapper.registerModule(brianModule);/*from   w ww .jav a  2  s . c o m*/
    mapper.registerModule(new Jdk8Module());

    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    df.setTimeZone(TimeZones.UNIVERSAL);
    mapper.setDateFormat(df);

    return mapper;
}

From source file:sg.yeefan.searchenginewrapper.clients.GoogleCustomClient.java

/**
 * Makes a query to Google Custom Search using a default query.
 *//*from w ww.j  a  v a  2s .c o m*/
private SearchEngineResults getResults(DefaultSearchEngineQuery query) throws SearchEngineException {
    if (query == null)
        throw new SearchEngineFatalException("Missing query.");
    String keyString = query.getKey();
    String label = query.getLabel();
    String queryString = query.getQuery();
    long startIndex = query.getStartIndex();
    String[] keyStrings = keyString.split("\\$", 0);
    if (keyStrings.length != 2)
        throw new SearchEngineFatalException("Key must be of the form: api_key + \"$\" + cx");
    String apiKey = keyStrings[0];
    String cx = keyStrings[1];
    if (startIndex < 1)
        throw new SearchEngineFatalException("Start index must be at least 1.");
    String encodedApiKey = null;
    String encodedCx = null;
    String encodedQuery = null;
    try {
        encodedApiKey = URLEncoder.encode(apiKey, "UTF-8");
        encodedCx = URLEncoder.encode(cx, "UTF-8");
        encodedQuery = URLEncoder.encode(queryString, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new SearchEngineFatalException(e);
    }
    long startTime = System.currentTimeMillis();
    FileDownloader downloader = new FileDownloader();
    String jsonString = null;
    try {
        downloader.setUserAgent(
                "Search Engine Wrapper (http://wing.comp.nus.edu.sg/~tanyeefa/downloads/searchenginewrapper/)");
        String requestUrl = "https://www.googleapis.com/customsearch/v1?key=" + encodedApiKey + "&cx="
                + encodedCx + "&q=" + encodedQuery + "&start=" + startIndex + "&num=10";
        byte[] bytes = downloader.download(requestUrl);
        jsonString = new String(bytes, "UTF-8");
    } catch (FileDownloaderException e) {
        // TODO: Handle response code and error stream to check
        // whether quota is exceeded.
        throw new SearchEngineException(e);
    } catch (UnsupportedEncodingException e) {
        throw new SearchEngineException(e);
    }
    long endTime = System.currentTimeMillis();
    Response response = null;
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        response = mapper.readValue(jsonString, Response.class);
    } catch (IOException e) {
        throw new SearchEngineException(e);
    }
    SearchEngineResults results = new SearchEngineResults();
    results.setLabel(label);
    results.setQuery(queryString);
    results.setTotalResults(response.getSearchInformation().getTotalResults());
    results.setStartIndex(startIndex);
    Item[] items = response.getItems();
    SearchEngineResult[] resultArray = new SearchEngineResult[items.length];
    for (int i = 0; i < items.length; i++) {
        String url = items[i].getLink();
        String title = items[i].getTitle();
        String snippet = items[i].getHtmlSnippet();
        resultArray[i] = new SearchEngineResult();
        resultArray[i].setURL(url);
        resultArray[i].setTitle(title);
        resultArray[i].setSnippet(processSnippet(snippet));
    }
    results.setResults(resultArray);
    results.setStartTime(startTime);
    results.setEndTime(endTime);
    if (items.length >= 10) {
        DefaultSearchEngineQuery nextQuery = new DefaultSearchEngineQuery();
        nextQuery.setKey(keyString);
        nextQuery.setLabel(label);
        nextQuery.setQuery(queryString);
        nextQuery.setStartIndex(startIndex + items.length);
        results.setNextQuery(nextQuery);
    }
    return results;
}