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

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

Introduction

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

Prototype

public ObjectMapper setDateFormat(DateFormat dateFormat) 

Source Link

Document

Method for configuring the default DateFormat to use when serializing time values as Strings, and deserializing from JSON Strings.

Usage

From source file:jeplus.JEPlusConfig.java

/**
 * Save this configuration to a JSON file
 * @param file The File object associated with the file to which the contents will be saved
 * @return Successful or not//  w  w  w .  j av  a 2s.c  om
 */
public boolean saveAsJSON(File file) {
    boolean success = true;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(format);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    try (FileOutputStream fw = new FileOutputStream(file);) {
        mapper.writeValue(fw, this);
        logger.info("Configuration saved to " + file.getAbsolutePath());
    } catch (Exception ex) {
        logger.error("Error saving configuration to JSON.", ex);
        success = false;
    }
    return success;
}

From source file:org.codemine.smartgarden.controller.SmartGardenServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w w  . j av  a2s  . c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    DateFormat chartDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    mapper.setDateFormat(chartDateFormat);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    RequestResult requestResult = new RequestResult();
    SmartGardenService smartGardenService = (SmartGardenService) request.getServletContext()
            .getAttribute(SERVICE_KEY);
    String action = (String) request.getParameter("action");
    if (action.equalsIgnoreCase("get_image")) {
        String filename = (String) request.getParameter("filename");
        File imageFile = smartGardenService.getImage(filename);
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        try (OutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(bufferedImage, "jpg", outputStream);
        }
        return;
    }
    try {

        if (!StringUtils.isEmpty(action)) {
            if (action.equalsIgnoreCase("start_irrigation")) {
                logger.log(Level.INFO, "processRequest:start_irrigation");
                requestResult = new RequestResult<Integer>();
                Integer historyId = smartGardenService.startIrrigationAsync(this.getDataSource());
                requestResult.setSuccess(true);
                requestResult.setValue(historyId);
            }
            if (action.equalsIgnoreCase("get_irrigation_history")) {
                logger.log(Level.INFO, "processRequest:get_irrigation_history");
                List<IrrigationHistory> historyList = smartGardenService
                        .getIrrigationHistoryList(this.getDataSource(), 10);
                requestResult.setValue(historyList);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("get_garden_status")) {
                logger.log(Level.INFO, "processRequest:get_garden_status");
                GardenStatus gardenStatus = smartGardenService.getGardenStatus(this.getDataSource());
                requestResult.setValue(gardenStatus);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("stop_irrigation")) {
                logger.log(Level.INFO, "processRequest:stop_irrigation");

                String historyIdParam = request.getParameter("historyId");
                Integer historyId = null;
                if (!StringUtils.isEmpty(historyIdParam)) {
                    historyId = Integer.parseInt(historyIdParam);
                }
                smartGardenService.stopIrrigation(this.getDataSource(), historyId);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("set_irrigation_duration")) {
                logger.log(Level.INFO, "processRequest:set_irrigation_duration");
                String irrigationDurationInSecond = (String) request.getParameter("duration");
                final long newIrrigationDurationInSecond = smartGardenService
                        .setIrrigationDuration(Integer.parseInt(irrigationDurationInSecond));
                requestResult.setSuccess(true);
                requestResult.setValue(newIrrigationDurationInSecond);
            }

            if (action.equalsIgnoreCase("get_soil_status_history")) {
                logger.log(Level.INFO, "processRequest:get_soil_status_history");
                List<SoilStatus> historyList = smartGardenService.getSoilStatusHistory(this.getDataSource(),
                        10);
                requestResult.setValue(historyList);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("get_power_status_history")) {
                logger.log(Level.INFO, "processRequest:get_power_status_history");
                List<PowerStatus> historyList = smartGardenService.getPowerStatusHistory(this.getDataSource(),
                        10);
                requestResult.setValue(historyList);
                requestResult.setSuccess(true);
            }

            if (action.equalsIgnoreCase("take_photo")) {
                logger.log(Level.INFO, "processRequest:take_photo");
                String photoFilename = smartGardenService.takePhoto();
                requestResult.setValue(photoFilename);
                requestResult.setSuccess(true);
            }

        } else {
            request.getRequestDispatcher("/index.html").forward(request, response);
        }
    } catch (Throwable t) {
        logger.log(Level.ERROR, "processRequest", t);
        requestResult.setSuccess(false);
        requestResult.setErrorMessage(t.toString());
    } finally {
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        String responseJSON = mapper.writeValueAsString(requestResult);
        out.print(responseJSON);
        out.flush();
        out.close();
    }

}

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 www .  ja v a  2 s .  c om*/
    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:com.unilever.audit.services2.Sync_Down.java

/**
 * Retrieves representation of an instance of
 * com.unilever.audit.services2.AuditResource
 *
 * @param id/*ww  w . j a va2 s. c o  m*/
 * @param dataType
 * @return an instance of java.lang.String
 */
@GET
@Path("getSyncObject/{id}/{dataType}/{compress}")
@Produces("application/json")
public byte[] getSyncObject(@PathParam("id") int id, @PathParam("dataType") String dataType,
        @PathParam("compress") int compress) {

    GZIPOutputStream gzip = null;
    count++;
    ByteArrayOutputStream out = null;
    SyncDownObjects syncDownObjects = getObject(dataType, id);

    try {
        out = new ByteArrayOutputStream();
        gzip = new GZIPOutputStream(out);

        ObjectMapper mapper = new ObjectMapper();
        AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
        AnnotationIntrospector introspector1 = new JacksonAnnotationIntrospector();
        mapper.setAnnotationIntrospectors(introspector, introspector1);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        //String jsonString = mapper.writeValueAsString(syncDownObjects);
        //JSONObject jsonobject = (JSONObject) new JSONParser().parse(jsonString);
        //gzip.write(jsonobject.toString().getBytes("8859_1"));
        //gzip.write(jsonobject.toString().getBytes("UTF-8"));
        gzip.write(mapper.writeValueAsBytes(syncDownObjects));
        gzip.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    } //catch (ParseException ex) {
      // ex.printStackTrace();
      // }
    System.out.println("======================= count : " + count);
    return out.toByteArray();
}

From source file:services.echannel.EchannelServiceImpl.java

/**
 * Initialize the service./*from   ww w  .  j  a va  2s . c o  m*/
 * 
 * @param lifecycle
 *            the Play life cycle service
 * @param configuration
 *            the Play configuration service
 * @param cache
 *            the Play cache service
 * @param preferenceManagerPlugin
 *            the preference service
 */

@Inject
public EchannelServiceImpl(ApplicationLifecycle lifecycle, Configuration configuration, CacheApi cache,
        IPreferenceManagerPlugin preferenceManagerPlugin) {
    Logger.info("SERVICE>>> EchannelServiceImpl starting...");

    this.echannelApiUrl = configuration.getString(Config.ECHANNEL_API_URL.getConfigurationKey());
    this.apiSecretKey = null;

    this.cache = cache;
    this.preferenceManagerPlugin = preferenceManagerPlugin;

    lifecycle.addStopHook(() -> {
        Logger.info("SERVICE>>> EchannelServiceImpl stopping...");
        Logger.info("SERVICE>>> EchannelServiceImpl stopped");
        return Promise.pure(null);
    });

    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat(AbstractApiController.DATE_FORMAT));
    this.mapper = mapper;

    Logger.info("SERVICE>>> EchannelServiceImpl started");
}

From source file:org.springframework.cloud.dataflow.rest.client.JobExecutionDeserializationTests.java

@Test
public void testDeserializationOfSingleJobExecution() throws IOException {

    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new Jackson2HalModule());

    final InputStream inputStream = JobExecutionDeserializationTests.class
            .getResourceAsStream("/SingleJobExecutionJson.txt");

    final String json = new String(StreamUtils.copyToByteArray(inputStream));

    objectMapper.addMixIn(JobExecution.class, JobExecutionJacksonMixIn.class);
    objectMapper.addMixIn(JobParameters.class, JobParametersJacksonMixIn.class);
    objectMapper.addMixIn(JobParameter.class, JobParameterJacksonMixIn.class);
    objectMapper.addMixIn(JobInstance.class, JobInstanceJacksonMixIn.class);
    objectMapper.addMixIn(StepExecution.class, StepExecutionJacksonMixIn.class);
    objectMapper.addMixIn(StepExecutionHistory.class, StepExecutionHistoryJacksonMixIn.class);
    objectMapper.addMixIn(ExecutionContext.class, ExecutionContextJacksonMixIn.class);
    objectMapper.addMixIn(ExitStatus.class, ExitStatusJacksonMixIn.class);
    objectMapper.setDateFormat(new ISO8601DateFormatWithMilliSeconds());

    final JobExecutionResource jobExecutionInfoResource = objectMapper.readValue(json,
            JobExecutionResource.class);

    Assert.assertNotNull(jobExecutionInfoResource);
    Assert.assertEquals(Long.valueOf(1), jobExecutionInfoResource.getJobId());
    Assert.assertEquals("ff.job", jobExecutionInfoResource.getName());
    Assert.assertEquals("COMPLETED", jobExecutionInfoResource.getJobExecution().getStatus().name());

}

From source file:com.rockagen.commons.util.JsonUtil.java

/**
 * Initialize mapper//from   w  ww.  j a  va  2 s.  co  m
 * 
 * @return initialized {@link ObjectMapper}
 */
private static ObjectMapper initMapper() {

    ObjectMapper mapper = new ObjectMapper();
    // to enable standard indentation ("pretty-printing"):
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    // to allow serialization of "empty" POJOs (no properties to serialize)
    // (without this setting, an exception is thrown in those cases)
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    // set writer flush after writer value
    mapper.enable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
    // ObjectMapper will call close() and root values that implement
    // java.io.Closeable;
    // including cases where exception is thrown and serialization does not
    // completely succeed.
    mapper.enable(SerializationFeature.CLOSE_CLOSEABLE);
    // to write java.util.Date, Calendar as number (timestamp):
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    // disable default date to timestamp
    mapper.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);

    // DeserializationFeature for changing how JSON is read as POJOs:

    // to prevent exception when encountering unknown property:
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    // disable default date to timestamp
    mapper.disable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS);
    // to allow coercion of JSON empty String ("") to null Object value:
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
    DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    // Set Default date fromat
    mapper.setDateFormat(df);

    return mapper;

}

From source file:jeplus.JEPlusProject.java

/**
 * Save this project to an XML file// w  w w  .j a v a  2 s  . co  m
 * @param file The File object associated with the file to which the contents will be saved
 * @return Successful or not
 */
public boolean saveAsJSON(File file) {
    boolean success = true;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(format);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    try (FileOutputStream fw = new FileOutputStream(file);) {
        mapper.writeValue(fw, this);
        logger.info("Project saved to " + file.getAbsolutePath());
    } catch (Exception ex) {
        logger.error("Error saving project to JSON.", ex);
        success = false;
    }
    return success;
}

From source file:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.java

/**
 * Configure an existing {@link ObjectMapper} instance with this builder's
 * settings. This can be applied to any number of {@code ObjectMappers}.
 * @param objectMapper the ObjectMapper to configure
 *///from   w  ww.j  a  va 2 s.  c  o  m
public void configure(ObjectMapper objectMapper) {
    Assert.notNull(objectMapper, "ObjectMapper must not be null");

    if (this.findModulesViaServiceLoader) {
        // Jackson 2.2+
        objectMapper.registerModules(ObjectMapper.findModules(this.moduleClassLoader));
    } else if (this.findWellKnownModules) {
        registerWellKnownModulesIfAvailable(objectMapper);
    }

    if (this.modules != null) {
        for (Module module : this.modules) {
            // Using Jackson 2.0+ registerModule method, not Jackson 2.2+ registerModules
            objectMapper.registerModule(module);
        }
    }
    if (this.moduleClasses != null) {
        for (Class<? extends Module> module : this.moduleClasses) {
            objectMapper.registerModule(BeanUtils.instantiateClass(module));
        }
    }

    if (this.dateFormat != null) {
        objectMapper.setDateFormat(this.dateFormat);
    }
    if (this.locale != null) {
        objectMapper.setLocale(this.locale);
    }
    if (this.timeZone != null) {
        objectMapper.setTimeZone(this.timeZone);
    }

    if (this.annotationIntrospector != null) {
        objectMapper.setAnnotationIntrospector(this.annotationIntrospector);
    }
    if (this.propertyNamingStrategy != null) {
        objectMapper.setPropertyNamingStrategy(this.propertyNamingStrategy);
    }
    if (this.defaultTyping != null) {
        objectMapper.setDefaultTyping(this.defaultTyping);
    }
    if (this.serializationInclusion != null) {
        objectMapper.setSerializationInclusion(this.serializationInclusion);
    }

    if (this.filters != null) {
        objectMapper.setFilterProvider(this.filters);
    }

    for (Class<?> target : this.mixIns.keySet()) {
        objectMapper.addMixIn(target, this.mixIns.get(target));
    }

    if (!this.serializers.isEmpty() || !this.deserializers.isEmpty()) {
        SimpleModule module = new SimpleModule();
        addSerializers(module);
        addDeserializers(module);
        objectMapper.registerModule(module);
    }

    customizeDefaultFeatures(objectMapper);
    for (Object feature : this.features.keySet()) {
        configureFeature(objectMapper, feature, this.features.get(feature));
    }

    if (this.handlerInstantiator != null) {
        objectMapper.setHandlerInstantiator(this.handlerInstantiator);
    } else if (this.applicationContext != null) {
        objectMapper.setHandlerInstantiator(
                new SpringHandlerInstantiator(this.applicationContext.getAutowireCapableBeanFactory()));
    }
}