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

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

Introduction

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

Prototype

public ObjectMapper enable(SerializationFeature f) 

Source Link

Document

Method for enabling specified DeserializationConfig feature.

Usage

From source file:com.simiacryptus.mindseye.models.Hdf5Archive.java

/**
 * Read JSON-formatted string attribute.
 *
 * @param attribute HDF5 attribute to read as JSON formatted string.
 * @return//ww w  .ja va 2s  . c om
 */
@Nullable
private String readAttributeAsJson(@Nonnull Attribute attribute) {
    VarLenType vl = attribute.getVarLenType();
    int bufferSizeMult = 1;
    @Nullable
    String s = null;
    /* TODO: find a less hacky way to do this.
     * Reading variable length strings (from attributes) is a giant
     * pain. There does not appear to be any way to determine the
     * length of the string in advance, so we use a hack: choose a
     * buffer size and read the config. If Jackson fails to parse
     * it, then we must not have read the entire config. Increase
     * buffer and repeat.
     */
    while (true) {
        @Nonnull
        byte[] attrBuffer = new byte[bufferSizeMult * 2000];
        @Nonnull
        BytePointer attrPointer = new BytePointer(attrBuffer);
        attribute.read(vl, attrPointer);
        attrPointer.get(attrBuffer);
        s = new String(attrBuffer);
        @Nonnull
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
        try {
            mapper.readTree(s);
            break;
        } catch (IOException e) {
        }
        bufferSizeMult++;
        if (bufferSizeMult > 100) {
            throw new RuntimeException("Could not read abnormally long HDF5 attribute");
        }
    }
    return s;
}

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;/*w  ww. j a v  a 2  s.c o  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:nu.yona.server.CoreConfiguration.java

@Bean
@Primary/*w  ww  .  j ava2  s  .co m*/
ObjectMapper objectMapper() {
    // HATEOAS disables the default Spring configuration options described at
    // https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper
    // See https://github.com/spring-projects/spring-hateoas/issues/333.
    // We fix this by applying the Spring configurator on the HATEOAS object mapper
    // See also
    // https://github.com/spring-projects/spring-boot/blob/v1.3.2.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java
    // which already seems to do this but does not work
    ObjectMapper springHateoasObjectMapper = beanFactory.getBean(SPRING_HATEOAS_OBJECT_MAPPER,
            ObjectMapper.class);
    Jackson2ObjectMapperBuilder builder = beanFactory.getBean(Jackson2ObjectMapperBuilder.class);
    builder.configure(springHateoasObjectMapper);

    // By default, Jackson converts dates to UTC. This causes issues when passing inactivity creation requests from the app
    // service to the analysis engine service.
    springHateoasObjectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

    // This way, the JsonView annotations on the controlers work properly
    springHateoasObjectMapper.enable(MapperFeature.DEFAULT_VIEW_INCLUSION);

    return springHateoasObjectMapper;
}

From source file:i5.las2peer.services.gamificationLevelService.GamificationLevelService.java

/**
 * Get a list of levels from database/*from w  w  w . ja v a2 s .  c  o  m*/
 * @param appId applicationId
 * @param currentPage current cursor page
 * @param windowSize size of fetched data
 * @param searchPhrase search word
 * @return HttpResponse Returned as JSON object
 */
@GET
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found a list of levels"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getLevelList", notes = "Returns a list of levels", response = LevelModel.class, responseContainer = "List")
public HttpResponse getLevelList(@ApiParam(value = "Application ID to return") @PathParam("appId") String appId,
        @ApiParam(value = "Page number for retrieving data") @QueryParam("current") int currentPage,
        @ApiParam(value = "Number of data size") @QueryParam("rowCount") int windowSize,
        @ApiParam(value = "Search phrase parameter") @QueryParam("searchPhrase") String searchPhrase) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "GET " + "gamification/levels/" + appId);

    List<LevelModel> model = null;
    Connection conn = null;

    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(this, Event.AGENT_GET_STARTED, "Get Levels");

        try {
            if (!levelAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get levels. App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
            objResponse.put("message",
                    "Cannot get levels. Cannot check whether application ID exist or not. Database error. "
                            + e1.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        int offset = (currentPage - 1) * windowSize;

        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        int totalNum = levelAccess.getNumberOfLevels(conn, appId);

        if (windowSize == -1) {
            offset = 0;
            windowSize = totalNum;
        }

        model = levelAccess.getLevelsWithOffsetAndSearchPhrase(conn, appId, offset, windowSize, searchPhrase);
        String modelString = objectMapper.writeValueAsString(model);
        JSONArray modelArray = (JSONArray) JSONValue.parse(modelString);
        logger.info(modelArray.toJSONString());
        objResponse.put("current", currentPage);
        objResponse.put("rowCount", windowSize);
        objResponse.put("rows", modelArray);
        objResponse.put("total", totalNum);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_30, "Levels fetched : " + appId + " : " + userAgent);
        L2pLogger.logEvent(this, Event.AGENT_GET_SUCCESS, "Levels fetched : " + appId + " : " + userAgent);
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {
        e.printStackTrace();
        // return HTTP Response on error
        objResponse.put("message", "Cannot get levels. Database error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get levels. JSON processing error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:synapticloop.scaleway.api.ScalewayApiClient.java

private ObjectMapper initializeObjectMapperJson() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
    mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper;
}

From source file:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java

/**
 * Function to be used by RMI, it returns achievement data with specific ID
 * @param appId applicationId//www  . j  a  v  a 2s . c om
 * @param achievementId achievementId
 * @return Serialized JSON achievement data 
 */
public String getAchievementWithIdRMI(String appId, String achievementId) {
    AchievementModel achievement;

    Connection conn = null;
    try {
        conn = dbm.getConnection();

        achievement = achievementAccess.getAchievementWithId(conn, appId, achievementId);
        if (achievement == null) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        String achievementString = objectMapper.writeValueAsString(achievement);
        return achievementString;
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
        //logger.warning("Get Achievement with ID RMI failed. " + e.getMessage());
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        return null;
        //logger.warning("Get Achievement with ID RMI failed. " + e.getMessage());
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }

}

From source file:i5.las2peer.services.gamificationLevelService.GamificationLevelService.java

/**
 * Get a level data with specific ID from database
 * @param appId applicationId/*from   w  ww.  ja  v a  2s. c  o m*/
 * @param levelNum level number
 * @return HttpResponse Returned as JSON object
 */
@GET
@Path("/{appId}/{levelNum}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found a level"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getlevelWithNum", notes = "Get level details with specific level number", response = LevelModel.class)
public HttpResponse getlevelWithNum(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Level number") @PathParam("levelNum") int levelNum) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "GET " + "gamification/levels/" + appId + "/" + levelNum);
    long randomLong = new Random().nextLong(); //To be able to match

    LevelModel level = null;
    Connection conn = null;

    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        try {
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_16, "" + randomLong);

            try {
                if (!levelAccess.isAppIdExist(conn, appId)) {
                    objResponse.put("message", "Cannot fetched level. App not found");
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
                objResponse.put("message",
                        "Cannot fetched level. Cannot check whether application ID exist or not. Database error. "
                                + e1.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
            if (!levelAccess.isLevelNumExist(conn, appId, levelNum)) {
                objResponse.put("message", "Cannot fetched level. level not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            level = levelAccess.getLevelWithNumber(conn, appId, levelNum);
            if (level != null) {
                ObjectMapper objectMapper = new ObjectMapper();
                //Set pretty printing of json
                objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

                String levelString = objectMapper.writeValueAsString(level);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_17, "" + randomLong);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_26, "" + name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_27, "" + appId);
                return new HttpResponse(levelString, HttpURLConnection.HTTP_OK);
            } else {
                objResponse.put("message", "Cannot fetched level. Cannot find level with " + levelNum);
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

            }
        } catch (SQLException e) {
            e.printStackTrace();
            objResponse.put("message", "Cannot fetched level. DB Error. " + e.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

        }

    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot fetched level. JSON processing error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot fetched level. DB Error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:i5.las2peer.services.gamificationActionService.GamificationActionService.java

/**
 * Function to be accessed via RMI to get list of action
 * @param appId applicationId/*w ww  .j a va 2s  .c  o m*/
 * @return serialized JSON notification data caused by triggered action
 */
public String getActionsRMI(String appId) {
    List<ActionModel> achs = null;
    Connection conn = null;

    try {
        conn = dbm.getConnection();
        JSONArray arr = new JSONArray();

        int offset = 0;
        int totalNum = actionAccess.getNumberOfActions(conn, appId);
        int windowSize = totalNum;

        achs = actionAccess.getActionsWithOffsetAndSearchPhrase(conn, appId, offset, windowSize, "");

        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        String actionString;
        try {
            actionString = objectMapper.writeValueAsString(achs);
            return actionString;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    } catch (SQLException e1) {
        e1.printStackTrace();
        return null;
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }

}

From source file:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java

/**
 * Get a list of achievements from database
 * @param appId applicationId/*  www . j a v a2 s .  c  o m*/
 * @param currentPage current cursor page
 * @param windowSize size of fetched data
 * @param searchPhrase search word
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found a list of achievements"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getAchievementList", notes = "Returns a list of achievements", response = AchievementModel.class, responseContainer = "List")
public HttpResponse getAchievementList(
        @ApiParam(value = "Application ID to return") @PathParam("appId") String appId,
        @ApiParam(value = "Page number for retrieving data") @QueryParam("current") int currentPage,
        @ApiParam(value = "Number of data size") @QueryParam("rowCount") int windowSize,
        @ApiParam(value = "Search phrase parameter") @QueryParam("searchPhrase") String searchPhrase) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "GET " + "gamification/achievements/" + appId);

    List<AchievementModel> achs = null;
    Connection conn = null;
    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();

        try {
            if (!achievementAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get achievements. App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
            objResponse.put("message",
                    "Cannot get achievements. Cannot check whether application ID exist or not. Database error. "
                            + e1.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        int offset = (currentPage - 1) * windowSize;
        int totalNum = achievementAccess.getNumberOfAchievements(conn, appId);

        if (windowSize == -1) {
            offset = 0;
            windowSize = totalNum;
        }

        achs = achievementAccess.getAchievementsWithOffsetAndSearchPhrase(conn, appId, offset, windowSize,
                searchPhrase);

        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        String achievementString = objectMapper.writeValueAsString(achs);
        JSONArray achievementArray = (JSONArray) JSONValue.parse(achievementString);
        logger.info(achievementArray.toJSONString());
        objResponse.put("current", currentPage);
        objResponse.put("rowCount", windowSize);
        objResponse.put("rows", achievementArray);
        objResponse.put("total", totalNum);
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get achievements. Database error. " + e.getMessage());
        // return HTTP Response on error
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get achievements. JSON processing error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}