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

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

Introduction

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

Prototype

public ObjectMapper registerModule(Module module) 

Source Link

Document

Method for registering a module that can extend functionality provided by this mapper; for example, by adding providers for custom serializers and deserializers.

Usage

From source file:org.efaps.esjp.admin.update.UpdatePack.java

/**
 * Check revisions./*ww  w. ja  v  a 2  s .c  o m*/
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @return the return
 * @throws EFapsException on error
 * @throws InstallationException on error
 */
public Return execute(final Parameter _parameter) throws EFapsException, InstallationException {
    final Context context = Context.getThreadContext();
    final Context.FileParameter fileItem = context.getFileParameters().get("pack");
    final boolean compress = GzipUtils.isCompressedFilename(fileItem.getName());

    try (final TarArchiveInputStream tarInput = new TarArchiveInputStream(
            compress ? new GzipCompressorInputStream(fileItem.getInputStream()) : fileItem.getInputStream());) {

        File tmpfld = AppConfigHandler.get().getTempFolder();
        if (tmpfld == null) {
            final File temp = File.createTempFile("eFaps", ".tmp");
            tmpfld = temp.getParentFile();
            temp.delete();
        }
        final File updateFolder = new File(tmpfld, Update.TMPFOLDERNAME);
        if (!updateFolder.exists()) {
            updateFolder.mkdirs();
        }
        final File dateFolder = new File(updateFolder, ((Long) new Date().getTime()).toString());
        dateFolder.mkdirs();

        final Map<String, URL> files = new HashMap<>();
        TarArchiveEntry currentEntry = tarInput.getNextTarEntry();
        while (currentEntry != null) {
            final byte[] bytess = new byte[(int) currentEntry.getSize()];
            tarInput.read(bytess);
            final File file = new File(dateFolder.getAbsolutePath() + "/" + currentEntry.getName());
            file.getParentFile().mkdirs();
            final FileOutputStream output = new FileOutputStream(file);
            output.write(bytess);
            output.close();
            files.put(currentEntry.getName(), file.toURI().toURL());
            currentEntry = tarInput.getNextTarEntry();
        }

        final Map<RevItem, InstallFile> installFiles = new HashMap<>();

        final URL json = files.get("revisions.json");
        final ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JodaModule());
        final List<RevItem> items = mapper.readValue(new File(json.toURI()),
                mapper.getTypeFactory().constructCollectionType(List.class, RevItem.class));
        final List<RevItem> allItems = new ArrayList<>();
        allItems.addAll(items);

        installFiles.putAll(getInstallFiles(files, items, CIAdmin.Abstract));
        installFiles.putAll(getInstallFiles(files, items, CIAdminUser.Abstract));
        installFiles.putAll(getInstallFiles(files, items, CIAdminAccess.AccessSet));
        installFiles.putAll(getInstallFiles(files, items, CICommon.DBPropertiesBundle));

        final Iterator<RevItem> iter = items.iterator();
        int i = 0;
        while (iter.hasNext()) {
            final RevItem item = iter.next();
            LOG.info("Adding unfound Item {} / {}: {}", i, items.size(), item.getIdentifier());
            final InstallFile installFile = new InstallFile().setName(item.getName4InstallFile())
                    .setURL(item.getURL(files)).setType(item.getFileType().getType())
                    .setRevision(item.getRevision()).setDate(item.getDate());
            installFiles.put(item, installFile);
            i++;
        }

        final List<InstallFile> installFileList = new ArrayList<>(installFiles.values());
        Collections.sort(installFileList, new Comparator<InstallFile>() {
            @Override
            public int compare(final InstallFile _installFile0, final InstallFile _installFile1) {
                return _installFile0.getName().compareTo(_installFile1.getName());
            }
        });

        final List<InstallFile> dependendFileList = new ArrayList<>();
        // check if a object that depends on another object must be added to the update
        final Map<String, String> depenMap = getDependendMap();
        final Set<String> tobeAdded = new HashSet<>();
        for (final RevItem item : installFiles.keySet()) {
            if (depenMap.containsKey(item.getIdentifier())) {
                tobeAdded.add(depenMap.get(item.getIdentifier()));
            }
        }
        if (!tobeAdded.isEmpty()) {
            // check if the object to be added is already part ot the list
            for (final RevItem item : installFiles.keySet()) {
                final Iterator<String> tobeiter = tobeAdded.iterator();
                while (tobeiter.hasNext()) {
                    final String ident = tobeiter.next();
                    if (item.getIdentifier().equals(ident)) {
                        tobeiter.remove();
                    }
                }
            }
        }
        if (!tobeAdded.isEmpty()) {
            i = 1;
            // add the objects to the list taht are missing
            for (final RevItem item : allItems) {
                if (tobeAdded.contains(item.getIdentifier())) {
                    LOG.info("Adding releated Item {} / {}: {}", i, tobeAdded.size(), item);
                    final InstallFile installFile = new InstallFile().setName(item.getName4InstallFile())
                            .setURL(item.getURL(files)).setType(item.getFileType().getType())
                            .setRevision(item.getRevision()).setDate(item.getDate());
                    dependendFileList.add(installFile);
                    i++;
                }
            }
        }

        if (!installFileList.isEmpty()) {
            final Install install = new Install(true);
            for (final InstallFile installFile : installFileList) {
                LOG.info("...Adding to Update: '{}' ", installFile.getName());
                install.addFile(installFile);
            }
            install.updateLatest(null);
        }
        if (!dependendFileList.isEmpty()) {
            LOG.info("Update for related Items");
            final Install install = new Install(true);
            for (final InstallFile installFile : dependendFileList) {
                LOG.info("...Adding to Update: '{}' ", installFile.getName());
                install.addFile(installFile);
            }
            install.updateLatest(null);
        }
        LOG.info("Terminated update.");
    } catch (final IOException e) {
        LOG.error("Catched", e);
    } catch (final URISyntaxException e) {
        LOG.error("Catched", e);
    }
    return new Return();
}

From source file:com.redhat.red.offliner.alist.FoloReportArtifactListReader.java

private ObjectMapper newObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT, true);

    mapper.enable(SerializationFeature.INDENT_OUTPUT, SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID);

    mapper.enable(MapperFeature.AUTO_DETECT_FIELDS);
    //        disable( MapperFeature.AUTO_DETECT_GETTERS );

    mapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES, SerializationFeature.WRITE_EMPTY_JSON_ARRAYS);

    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    mapper.registerModule(new FoloSerializerModule());

    return mapper;
}

From source file:org.bonitasoft.web.designer.config.DesignerConfig.java

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    //By default all properties without explicit view definition are included in serialization.
    //To use JsonView we have to change this parameter
    objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);

    //We don't have to serialize null values
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.registerModule(new JodaModule());
    objectMapper.registerSubtypes(jacksonSubTypes());

    //add Handler to migrate old json
    objectMapper.addHandler(new JacksonDeserializationProblemHandler());

    return objectMapper;
}

From source file:com.infinities.nova.util.jackson.JacksonProvider.java

public JacksonProvider() {
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
    // if using BOTH JAXB annotations AND Jackson annotations:
    AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();

    ObjectMapper mapper = new ObjectMapper().registerModule(new Hibernate4Module())
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"))
            .enable(SerializationFeature.INDENT_OUTPUT)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .setAnnotationIntrospector(new AnnotationIntrospectorPair(introspector, secondary));
    NullStringSerializer serializer = new NullStringSerializer();

    SimpleModule module = new SimpleModule("NullToNoneDeserializer");
    module.addSerializer(String.class, serializer);
    mapper.registerModule(module);
    // mapper = mapper.setSerializationInclusion(Include)
    setMapper(mapper);/*from  ww  w  .j  a v  a2  s.c  om*/
}

From source file:de.undercouch.bson4jackson.BsonParserTest.java

private <T> T parseBsonObject(BSONObject o, Class<T> cls, Module... modules) throws IOException {
    BSONEncoder enc = new BasicBSONEncoder();
    byte[] b = enc.encode(o);

    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    BsonFactory fac = new BsonFactory();
    ObjectMapper mapper = new ObjectMapper(fac);
    if (modules != null) {
        for (Module mod : modules) {
            mapper.registerModule(mod);
        }/*from   ww  w  .  j  a v a 2s.com*/
    }
    fac.setCodec(mapper);
    return mapper.readValue(bais, cls);
}

From source file:ijfx.ui.canvas.FxCanvasTester.java

@Override
public void start(Stage primaryStage) {

    final SCIFIO scifio = new SCIFIO();
    MenuBar menuBar = new MenuBar();
    InputControl parameterInput = null;/*from  w  w w .ja  va2  s. co  m*/
    try {
        System.setProperty("imagej.legacy.sync", "true");
        //reader.getContext().inject(this);
        ImageJ imagej = new ImageJ();
        context = imagej.getContext();
        CommandInfo command = imagej.command().getCommand(GaussianBlur.class);

        CommandModuleItem input = command.getInput("sigma");
        Class<?> type = input.getType();
        if (type == double.class) {
            type = Double.class;
        }

        context.inject(this);

        GaussianBlur module = new GaussianBlur();

        imagej.ui().showUI();

        //reader = scifio.initializer().initializeReader("./stack.tif");
        commandService.run(OpenFile.class, true, new HashMap<String, Object>());

        menuBar = new MenuBar();
        menuService.createMenus(new FxMenuCreator(), menuBar);
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule simpleModule = new SimpleModule("ModuleSerializer");
        // simpleModule.addSerializer(ModuleItem<?>.class,new ModuleItemSerializer());
        simpleModule.addSerializer(ModuleInfo.class, new ModuleSerializer());
        simpleModule.addSerializer(ModuleItem.class, new ModuleItemSerializer());
        mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.registerModule(simpleModule);

        mapper.writeValue(new File("modules.json"), moduleService.getModules());

    } catch (Exception ex) {
        ImageJFX.getLogger();
    }

    //imageView.fitImageToScreen();
    Button reset = new Button("Reset");

    reset.setOnAction(event -> update());

    BorderPane pane = new BorderPane();

    Button test = new Button("Test");

    AnchorPane root = new AnchorPane();
    root.getChildren().add(pane);
    root.getStylesheets().add(ArcMenu.class.getResource("arc-default.css").toExternalForm());
    root.getStylesheets().add(ImageJFX.class.getResource(("flatterfx.css")).toExternalForm());
    AnchorPane.setTopAnchor(pane, 0.0);
    AnchorPane.setBottomAnchor(pane, 0.0);
    AnchorPane.setLeftAnchor(pane, 0.0);
    AnchorPane.setRightAnchor(pane, 0.0);
    pane.setTop(menuBar);

    HBox vbox = new HBox();
    vbox.getChildren().addAll(reset, test, parameterInput);
    vbox.setSpacing(10);
    vbox.setPadding(new Insets(10, 10, 10, 10));
    // update();
    pane.setCenter(ImageWindowContainer.getInstance());
    // pane.setPrefSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
    pane.setBottom(vbox);

    Scene scene = new Scene(root, 600, 600);

    test.setOnAction(event -> {

        test();
    });

    primaryStage.setTitle("ImageCanvasTest");
    primaryStage.setScene(scene);
    primaryStage.show();
}

From source file:org.apache.drill.exec.store.parquet.metadata.Metadata.java

private void writeFile(ParquetTableMetadataDirs parquetTableMetadataDirs, Path p, FileSystem fs)
        throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false);
    jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    SimpleModule module = new SimpleModule();
    mapper.registerModule(module);
    FSDataOutputStream os = fs.create(p);
    mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadataDirs);
    os.flush();//from   www.ja va  2 s  .co  m
    os.close();
}

From source file:eu.trentorise.opendata.jackan.CkanClient.java

/**
 * Configures the provided Jackson ObjectMapper exactly as the internal JSON
 * mapper used for reading operations. If you want to perform
 * create/update/delete operations, use/*from ww  w .  j a v a 2 s. c  o  m*/
 * {@link #configureObjectMapperForPosting(com.fasterxml.jackson.databind.ObjectMapper, java.lang.Class) }
 * instead.
 *
 * @param om
 *            a Jackson object mapper
 * @since 0.4.1
 */
public static void configureObjectMapper(ObjectMapper om) {
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    om.registerModule(new JackanModule());
}

From source file:eu.trentorise.opendata.semtext.jackson.test.SemTextModuleTest.java

@Test
public void testMetadataSerializationSimple() throws JsonProcessingException, IOException {
    ObjectMapper om = new ObjectMapper();

    // register all required modules into the Jackson Object Mapper
    SemTextModule.registerModulesInto(om);

    // declare that metadata under namespace 'testns' in SemText objects should be deserialized into a Date object
    SemTextModule.registerMetadata(SemText.class, "testns", Date.class);

    // Let's say MyMetadata is tricky to deserialize, so we tell Jackson how to deserialize it with a mixin annotation
    om.registerModule(new SimpleModule() {
        {/*from   w w  w . j  a v a  2  s  . co m*/
            setMixInAnnotation(MyMetadata.class, MyMetadataJackson.class);
        }
    });

    String json = om.writeValueAsString(SemText.of("ciao").withMetadata("testns", new Date(123)));

    LOG.fine("json = " + json);

    SemText reconstructedSemText = om.readValue(json, SemText.class);

    Date reconstructedMetadata = (Date) reconstructedSemText.getMetadata("testns");

    assert new Date(123).equals(reconstructedMetadata);
}

From source file:eu.trentorise.opendata.semtext.jackson.test.SemTextModuleTest.java

@Test
public void testMetadataSerializationComplex() throws JsonProcessingException, IOException {
    ObjectMapper om = new ObjectMapper();

    // register all required modules into the Jackson Object Mapper
    SemTextModule.registerModulesInto(om);

    // declare that metadata under namespace 'testns' in SemText objects should be deserialized into a MyMetadata object
    SemTextModule.registerMetadata(SemText.class, "testns", MyMetadata.class);

    // Let's say MyMetadata is tricky to deserialize, so we tell Jackson how to deserialize it with a mixin annotation
    om.registerModule(new SimpleModule() {
        {/*from   w w w  .  jav  a 2s.  c o  m*/
            setMixInAnnotation(MyMetadata.class, MyMetadataJackson.class);
        }
    });

    String json = om.writeValueAsString(
            SemText.of(Locale.ITALIAN, "ciao").withMetadata("testns", MyMetadata.of("hello")));

    SemText reconstructedSemText = om.readValue(json, SemText.class);

    MyMetadata reconstructedMetadata = (MyMetadata) reconstructedSemText.getMetadata("testns");

    assert MyMetadata.of("hello").equals(reconstructedMetadata);
}