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:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java

/**
 * Get an achievement data with specific ID from database
 * @param appId applicationId/* w w  w .jav  a  2s  .  c  o m*/
 * @param achievementId achievement id
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}/{achievementId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found an achievement"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getAchievementWithId", notes = "Get achievement data with specified ID", response = AchievementModel.class)
public HttpResponse getAchievementWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Achievement ID") @PathParam("achievementId") String achievementId) {

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

    AchievementModel achievement = 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(Event.SERVICE_CUSTOM_MESSAGE_16, "" + randomLong);

        try {

            try {
                if (!achievementAccess.isAppIdExist(conn, appId)) {
                    objResponse.put("message", "Cannot get achievement detail. 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 achievement detail. 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 (!achievementAccess.isAchievementIdExist(conn, appId, achievementId)) {
                objResponse.put("message", "Cannot get achievement detail. Achievement not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            achievement = achievementAccess.getAchievementWithId(conn, appId, achievementId);
            if (achievement == null) {
                objResponse.put("message", "Achievement Null, Cannot find achievement with " + achievementId);
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            //Set pretty printing of json
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

            String achievementString = objectMapper.writeValueAsString(achievement);
            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(achievementString, HttpURLConnection.HTTP_OK);
        } catch (SQLException e) {
            e.printStackTrace();
            objResponse.put("message", "Cannot get achievement detail. 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 get achievement detail. 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 get achievement. Failed to fetch " + achievementId + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    }
}

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

/**
 * Get a list of actions from database/*ww w .  j ava2s.  com*/
 * @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 actions"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getActionList", notes = "Returns a list of actions", response = ActionModel.class, responseContainer = "List")
public HttpResponse getActionList(@ApiParam(value = "Application ID") @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/actions/" + appId);

    List<ActionModel> 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();
        L2pLogger.logEvent(this, Event.AGENT_GET_STARTED, "Get Actions");

        try {
            if (!actionAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get actions. 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 actions. 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 = actionAccess.getNumberOfActions(conn, appId);

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

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

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

        String actionString = objectMapper.writeValueAsString(achs);
        JSONArray actionArray = (JSONArray) JSONValue.parse(actionString);
        logger.info(actionArray.toJSONString());
        objResponse.put("current", currentPage);
        objResponse.put("rowCount", windowSize);
        objResponse.put("rows", actionArray);
        objResponse.put("total", totalNum);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_10,
                "Actions fetched" + " : " + appId + " : " + userAgent);
        L2pLogger.logEvent(this, Event.AGENT_GET_SUCCESS,
                "Actions 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 actions. 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 actions. 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);
        }
    }
}

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

/**
 * Get an action data with specific ID from database
 * @param appId applicationId/*from  w  w  w  .j  av a2  s.c o  m*/
 * @param actionId action id
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}/{actionId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found an action"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "Find action for specific App ID and action ID", notes = "Returns a action", response = ActionModel.class, authorizations = @Authorization(value = "api_key"))
public HttpResponse getActionWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Action ID") @PathParam("actionId") String actionId) {

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

    ActionModel action = 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(Event.SERVICE_CUSTOM_MESSAGE_16, "" + randomLong);

        try {

            try {
                if (!actionAccess.isAppIdExist(conn, appId)) {
                    objResponse.put("message", "Cannot get action. 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 action. 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 (!actionAccess.isActionIdExist(conn, appId, actionId)) {
                objResponse.put("message", "Cannot get action. Action not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            action = actionAccess.getActionWithId(conn, appId, actionId);
            if (action != null) {
                ObjectMapper objectMapper = new ObjectMapper();
                //Set pretty printing of json
                objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

                String actionString = objectMapper.writeValueAsString(action);
                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(actionString, HttpURLConnection.HTTP_OK);
            } else {
                objResponse.put("message", "Cannot get action. Cannot find badge with " + actionId);
                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 get action. 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 get action. 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 get action. 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.gamificationQuestService.GamificationQuestService.java

/**
 * RMI function to get quest detail with specific ID
 * @param appId applicationId//from   w  w  w .  j a  v  a  2s .c  o  m
 * @param questId questId
 * @return Serialized JSON string of a quest detail
 */
public String getQuestWithIdRMI(String appId, String questId) {
    QuestModel quest;
    Connection conn = null;

    try {
        conn = dbm.getConnection();
        quest = questAccess.getQuestWithId(conn, appId, questId);
        if (quest == null) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

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

From source file:uniko.west.topology.bolts.DiscussionTreeBolt.java

/**
 * searches for locations in the message and computes related locations
 *
 * @param input// w w  w .  jav a 2 s .c o  m
 *            standard Storm tuple input object (passed within Storm
 *            topology itself, not be a user)
 */
@Override
public void execute(Tuple input) {
    // Retrieve hash map tuple object from Tuple input at index 0, index 1
    // will be message delivery tag (not used here)
    Map<Object, Object> inputMap = (HashMap<Object, Object>) input.getValue(0);
    // Get JSON object from the HashMap from the Collections.singletonList
    Map<Object, Object> message = (Map<Object, Object>) inputMap.get("message");

    // Acknowledge the collector that we actually received the input
    this.collector.ack(input);

    if (!message.containsKey("created_at")) {
        return; // skip delete messages
    }
    // Print received message
    // this.logger.info("Received message: " + message.toJSONString());

    String timeStamp = (String) message.get("created_at");
    DateTime timestamp = DateTime.parse(timeStamp,
            DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss Z yyyy").withLocale(Locale.US));

    if (this.bufferStartTime == null) {
        this.bufferStartTime = timestamp;
        this.deadline = this.bufferStartTime.plusMinutes(this.intervalInMinutes);
    }

    String authorId = (String) ((Map<Object, Object>) message.get("user")).get("id_str");
    String authorScreenName = (String) ((Map<Object, Object>) message.get("user")).get("screen_name");
    String text = (String) message.get("text");
    String tweetId = (String) message.get("id_str");
    boolean retweet = false;

    String ancestorTweetId = (String) message.get("in_reply_to_status_id_str");
    String ancestorAuthorId = (String) message.get("in_reply_to_user_id_str");
    String ancestorAutorScreenName = (String) message.get("in_reply_to_screen_name");

    Map<Object, Object> retweeted_status = (Map<Object, Object>) message.get("retweeted_status");
    if (retweeted_status != null) {
        retweet = true;
        ancestorTweetId = (String) ((Map<Object, Object>) message.get("retweeted_status")).get("id_str");
    }

    Tweet tweet = new Tweet(authorId, authorScreenName, tweetId, timestamp, text, ancestorTweetId, true,
            retweet);

    if (ancestorTweetId != null) {
        if (this.rootTweetsMap.containsKey(tweet.getIn_reply_to())) {
            this.rootTweetsMap.get(tweet.getIn_reply_to()).getReplies().add(tweet);
        } else if (this.childrenTweetsMap.containsKey(tweet.getIn_reply_to())) {
            this.childrenTweetsMap.get(tweet.getIn_reply_to()).getReplies().add(tweet);
        } else {
            // tweet is a reply or retweet but its ancestor was'nt observed
            // by this bolt, therefore its ancestor is treated as a dummy
            // entry
            Tweet dummyTweet = new Tweet(ancestorAuthorId, ancestorAutorScreenName, ancestorTweetId, null, null,
                    null, false, false);
            dummyTweet.getReplies().add(tweet);
            this.rootTweetsMap.put(ancestorTweetId, dummyTweet);
        }
        this.childrenTweetsMap.put(tweetId, tweet);
    } else {
        // tweet is no reply or retweet
        this.rootTweetsMap.put(tweetId, tweet);
    }

    if (timestamp.isAfter(this.deadline) || timestamp.isEqual(this.deadline)) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String jsonResultString;
            HashMap<String, Object> jsonResult = new HashMap<>();
            jsonResult.put("start", this.bufferStartTime.toString());
            jsonResult.put("end", timestamp.toString());
            jsonResult.put("result", this.rootTweetsMap.values());
            jsonResultString = mapper.writeValueAsString(jsonResult);
            Logger.getLogger(DiscussionTreeBolt.class.getName()).log(Level.INFO,
                    "Deadline expired, Buffer size : " + this.rootTweetsMap.size());
            this.collector.emit(new Values(jsonResultString));
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            mapper.writeValue(
                    new File("/home/martin/test/discussionTreeBolt/discussionTree-" + this.bufferStartTime),
                    jsonResult);
            this.bufferStartTime = null;
            this.rootTweetsMap = new LinkedHashMap<>();
            this.childrenTweetsMap = new HashMap<>();
        } catch (JsonProcessingException ex) {
            Logger.getLogger(DiscussionTreeBolt.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DiscussionTreeBolt.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:i5.las2peer.services.gamificationQuestService.GamificationQuestService.java

/**
 * Get a quest data with specific ID from database
 * @param appId applicationId//from ww  w. j a  v a 2s  . co m
 * @param questId quest id
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}/{questId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found a quest"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getQuestWithId", notes = "Returns quest detail with specific ID", response = QuestModel.class)
public HttpResponse getQuestWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Quest ID") @PathParam("questId") String questId) {

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

    QuestModel quest = 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(Event.SERVICE_CUSTOM_MESSAGE_16, "" + randomLong);

        try {
            if (!questAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get quest. 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 quest. 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 (!questAccess.isQuestIdExist(conn, appId, questId)) {
            objResponse.put("message", "Cannot get quest. Quest not found");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
        quest = questAccess.getQuestWithId(conn, appId, questId);

        if (quest == null) {
            objResponse.put("message", "Cannot get quest. Quest Null, Cannot find quest with " + questId);
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        String questString = objectMapper.writeValueAsString(quest);
        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(questString, HttpURLConnection.HTTP_OK);

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

    } catch (IOException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get quest. Problem in the quest model. " + 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:i5.las2peer.services.gamificationQuestService.GamificationQuestService.java

/**
 * Get a list of quests from database//www.ja v  a  2s.  co 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 quests"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getQuestList", notes = "Returns a list of quests", response = QuestModel.class, responseContainer = "List")
public HttpResponse getQuestList(@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/quests/" + appId);

    List<QuestModel> qs = 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 (!questAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get quests. 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 quests. 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 = questAccess.getNumberOfQuests(conn, appId);

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

        qs = questAccess.getQuestsWithOffsetAndSearchPhrase(conn, appId, offset, windowSize, searchPhrase);

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

        String questString = objectMapper.writeValueAsString(qs);
        JSONArray questArray = (JSONArray) JSONValue.parse(questString);
        //logger.info(questArray.toJSONString());

        for (int i = 0; i < qs.size(); i++) {
            JSONArray actionArray = listPairtoJSONArray(qs.get(i).getActionIds());

            JSONObject questObject = (JSONObject) questArray.get(i);

            questObject.replace("actionIds", actionArray);

            questArray.set(i, questObject);
        }

        objResponse.put("current", currentPage);
        objResponse.put("rowCount", windowSize);
        objResponse.put("rows", questArray);
        objResponse.put("total", totalNum);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_37,
                "Quests fetched" + " : " + appId + " : " + userAgent);
        L2pLogger.logEvent(this, Event.AGENT_GET_SUCCESS, "Quests 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 quests. 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 quests. JSON process error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (IOException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get quests. IO Exception. " + 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:com.github.FraggedNoob.GitLabTransfer.GitlabRelatedData.java

/**
 * Saves all the data to JSON files except for the hostUrl, projectName,
 * and apiToken.//from w  w  w .  ja  va 2s .c  o m
 * @param filepath The filepath prefix
 * @return T=success, F=fail
 */
public boolean saveAllData(String filepath) {

    ObjectMapper mapper = new ObjectMapper();

    // Always the output pretty.
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    File w;
    String wname = "(none)";

    w = createFileForWriting(filepath, "_project");
    if (w == null) {
        return false;
    }

    // Project 
    try {
        mapper.writeValue(w, project);
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error writing to project to %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Wrote project (%s) to %s.\n", projectName, wname);

    // Users
    w = createFileForWriting(filepath, "_users");
    if (w == null) {
        return false;
    }
    try {
        mapper.writeValue(w, users);
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error writing to users to %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Wrote users to %s.\n", wname);

    // Milestones
    w = createFileForWriting(filepath, "_milestones");
    if (w == null) {
        return false;
    }
    try {
        // Set to List
        mapper.writeValue(w, new ArrayList<GitlabMilestone>(milestones));
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error writing to milestones to %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Wrote milestones to %s.\n", wname);

    // Issues
    w = createFileForWriting(filepath, "_issues");
    if (w == null) {
        return false;
    }
    try {
        // Set to List
        mapper.writeValue(w, new ArrayList<GitlabIssue>(issues));
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error writing to issues to %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Wrote issues to %s.\n", wname);

    // Issue Notes
    w = createFileForWriting(filepath, "_inotes");
    if (w == null) {
        return false;
    }
    try {
        // Map of Integer,Set to Integer,List
        Map<Integer, List<GitlabNote>> mapList = new TreeMap<Integer, List<GitlabNote>>();
        for (Integer k : issueNotes.keySet()) {
            mapList.put(k, new ArrayList<GitlabNote>(issueNotes.get(k)));
        }

        mapper.writeValue(w, mapList);
        wname = w.getCanonicalPath();
    } catch (IOException e) {
        System.out.printf("Error writing to issues to %s.\n", wname);
        e.printStackTrace();
        return false;
    }

    System.out.printf("Wrote issue notes to %s.\n", wname);

    System.out.printf("Writing to files complete.\n");

    return true;
}

From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * RMI function to get badge data detail with specific ID
 * @param appId application id/*w  w  w.  j a  va  2  s  .  c o  m*/
 * @param badgeId badge id
 * @return serialized JSON badge data
 */
public String getBadgeWithIdRMI(String appId, String badgeId) {
    BadgeModel badge;
    Connection conn = null;

    try {
        conn = dbm.getConnection();
        badge = badgeAccess.getBadgeWithId(conn, appId, badgeId);
        if (badge == null) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

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

From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java

/**
 * Get all application list separated into two categories. All apps registered for the member and other apps.
 * //from   w  w  w  .j  a v a 2s.  com
 * 
 * @return HttpResponse with the returnString
 */
@GET
@Path("/list/separated")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "getSeparateApplicationInfo", notes = "Get all application list separated into two categories. All apps registered for the member and other apps.")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "List of apps"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database error"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "JsonProcessingException") })
public HttpResponse getSeparateApplicationInfo() {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "GET " + "gamification/applications/list/separated");

    JSONObject objResponse = new JSONObject();
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    ObjectMapper objectMapper = new ObjectMapper();
    //Set pretty printing of json
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    try {
        conn = dbm.getConnection();
        List<List<ApplicationModel>> allApps = applicationAccess.getSeparateApplicationsWithMemberId(conn,
                name);

        try {
            String response = objectMapper.writeValueAsString(allApps);
            allApps.clear();
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_11, "" + name);

            return new HttpResponse(response, HttpURLConnection.HTTP_OK);

        } catch (JsonProcessingException e) {
            e.printStackTrace();

            allApps.clear();
            // return HTTP Response on error
            objResponse.put("message", "Cannot delete Application. JsonProcessingException." + e.getMessage());
            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", "Database error");
        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);
        }
    }

}