List of usage examples for com.fasterxml.jackson.databind ObjectMapper enable
public ObjectMapper enable(SerializationFeature f)
From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java
/** * Get an app data with specified ID/* w w w . j a va 2 s . c o m*/ * @param appId applicationId * @return Application data in JSON */ @GET @Path("/data/{appId}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "getApplicationDetails", notes = "Get an application data with specific ID") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Return application data with specific ID"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Method not found"), @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App not found"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database Error"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Failed to process JSON") }) public HttpResponse getApplicationDetails( @ApiParam(value = "Application ID", required = true) @PathParam("appId") String appId) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "GET " + "gamification/applications/data/" + appId); JSONObject objResponse = new JSONObject(); Connection conn = null; UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } try { conn = dbm.getConnection(); if (!applicationAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot get Application detail. App not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } // Add Member to App ApplicationModel app = applicationAccess.getApplicationWithId(conn, appId); ObjectMapper objectMapper = new ObjectMapper(); //Set pretty printing of json objectMapper.enable(SerializationFeature.INDENT_OUTPUT); String appString = objectMapper.writeValueAsString(app); return new HttpResponse(appString, HttpURLConnection.HTTP_OK); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot get Application detail. 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 Application detail. Failed to process JSON. " + 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.gamificationBadgeService.GamificationBadgeService.java
/** * Get a badge data with specific ID from database * @param appId applicationId//from w w w. j a v a 2 s . c o m * @param badgeId badge id * @return HttpResponse returned as JSON object */ @GET @Path("/{appId}/{badgeId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found a badges"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") }) @ApiOperation(value = "Find point for specific App ID and badge ID", notes = "Returns a badge", response = BadgeModel.class, responseContainer = "List", authorizations = @Authorization(value = "api_key")) public HttpResponse getBadgeWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId, @ApiParam(value = "Badge ID") @PathParam("badgeId") String badgeId) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "GET " + "gamification/badges/" + appId + "/" + badgeId); long randomLong = new Random().nextLong(); //To be able to match BadgeModel badge = 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 (!badgeAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot get badge. 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 badge. 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); } badge = badgeAccess.getBadgeWithId(conn, appId, badgeId); if (badge == null) { objResponse.put("message", "Cannot get badge. Badge model is null."); 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 badgeString = objectMapper.writeValueAsString(badge); 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(badgeString, HttpURLConnection.HTTP_OK); } catch (JsonProcessingException e) { e.printStackTrace(); objResponse.put("message", "Cannot get badge. Cannot process JSON." + 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 badge. Database 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:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java
/** * Get a list of badges from database/*from ww w. j av a2s . com*/ * @param appId application id * @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_INTERNAL_ERROR, message = "Internal Error"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Badge not found"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") }) @ApiOperation(value = "Find badges for specific App ID", notes = "Returns a list of badges", response = BadgeModel.class, responseContainer = "List", authorizations = @Authorization(value = "api_key")) public HttpResponse getBadgeList( @ApiParam(value = "Application ID that contains badges", required = true) @PathParam("appId") String appId, @ApiParam(value = "Page number cursor for retrieving data") @QueryParam("current") int currentPage, @ApiParam(value = "Number of data size per fetch") @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/badges/" + appId); List<BadgeModel> badges = 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 Badges"); try { if (!badgeAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot get badges. 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(); logger.info( "Cannot check whether application ID exist or not. Database error. >> " + e1.getMessage()); objResponse.put("message", "Cannot get badges. 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); } // Check app id exist or not int offset = (currentPage - 1) * windowSize; int totalNum = badgeAccess.getNumberOfBadges(conn, appId); if (windowSize == -1) { offset = 0; windowSize = totalNum; } badges = badgeAccess.getBadgesWithOffsetAndSearchPhrase(conn, appId, offset, windowSize, searchPhrase); ObjectMapper objectMapper = new ObjectMapper(); //Set pretty printing of json objectMapper.enable(SerializationFeature.INDENT_OUTPUT); String badgeString = objectMapper.writeValueAsString(badges); JSONArray badgeArray = (JSONArray) JSONValue.parse(badgeString); objResponse.put("current", currentPage); objResponse.put("rowCount", windowSize); objResponse.put("rows", badgeArray); objResponse.put("total", totalNum); logger.info(objResponse.toJSONString()); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "Badges fetched" + " : " + appId + " : " + userAgent); L2pLogger.logEvent(this, Event.AGENT_GET_SUCCESS, "Badges fetched" + " : " + appId + " : " + userAgent); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot get badges. Internal Error. Database connection failed. " + 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 badges. Cannot connect to database. " + 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:jeplus.JEPlusProject.java
/** * Save this project to an XML file//from w w w. j ava2 s. c om * @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:jonelo.jacksum.concurrent.Jacksum2Cli.java
public int printResults() { try {/*from www . j a va 2 s . c om*/ if (this.isHelp()) { this.printHelp(); return OK; } this.initOutput(); if (this.isPrintMetainfo()) { final HashFormat simpleFormat = new SimpleHashFormat(this.getEncoding(), this.getHexaGroupSize(), this.getHexaGroupSeparatorChar(), null); final ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); final JacksumReport report = new JacksumReport(); report.setAlgorithms( this.algorithms.stream().map(algo -> algo.getCanonicalName()).collect(Collectors.toList())); report.setAlternative(this.alternative); report.setEncoding(this.getEncoding().getValue()); report.setHexaGroupSeparatorChar(this.hexaGroupSeparatorChar); report.setHexaGroupSize(this.hexaGroupSize); report.setPathSeparator(this.separator); if (this.quickSequence != null) { this.buildQuickReport(report, simpleFormat); mapper.writeValue(this.out, report); return OK; } //process files this.buildFilesReport(report, simpleFormat); mapper.enable(SerializationFeature.INDENT_OUTPUT).writeValue(this.out, report); return OK; } if (this.quickSequence != null) { this.out.println(this.getFormattedQuickHash()); return OK; } for (String resultString : this.getFormattedFileHashes()) { this.out.println(resultString); } return OK; } catch (Throwable ex) { this.printError(ex.getMessage()); return ERROR_STATUS; } }
From source file:org.apache.asterix.test.common.ResultExtractor.java
public static InputStream extract(InputStream resultStream) throws Exception { ObjectMapper om = new ObjectMapper(); String resultStr = IOUtils.toString(resultStream, Charset.defaultCharset()); PrettyPrinter singleLine = new SingleLinePrettyPrinter(); ObjectNode result = om.readValue(resultStr, ObjectNode.class); LOGGER.fine("+++++++\n" + result + "\n+++++++\n"); String type = ""; String status = ""; String results = ""; String field = ""; for (Iterator<String> sIter = result.fieldNames(); sIter.hasNext();) { field = sIter.next();/*from w ww.j av a2 s . co m*/ switch (field) { case "requestID": break; case "clientContextID": break; case "signature": break; case "status": status = om.writeValueAsString(result.get(field)); break; case "type": type = om.writeValueAsString(result.get(field)); break; case "metrics": LOGGER.fine(om.writeValueAsString(result.get(field))); break; case "errors": JsonNode errors = result.get(field).get(0).get("msg"); throw new AsterixException(errors.asText()); case "results": if (result.get(field).size() <= 1) { if (result.get(field).size() == 0) { results = ""; } else if (result.get(field).isArray()) { if (result.get(field).get(0).isTextual()) { results = result.get(field).get(0).asText(); } else { ObjectMapper omm = new ObjectMapper(); omm.setDefaultPrettyPrinter(singleLine); omm.enable(SerializationFeature.INDENT_OUTPUT); results = omm.writer(singleLine).writeValueAsString(result.get(field)); } } else { results = om.writeValueAsString(result.get(field)); } } else { StringBuilder sb = new StringBuilder(); JsonNode[] fields = Iterators.toArray(result.get(field).elements(), JsonNode.class); if (fields.length > 1) { for (JsonNode f : fields) { if (f.isObject()) { sb.append(om.writeValueAsString(f)); } else { sb.append(f.asText()); } } } results = sb.toString(); } break; default: throw new AsterixException("Unanticipated field \"" + field + "\""); } } return IOUtils.toInputStream(results); }
From source file:org.apache.kylin.tool.CubeMetaExtractor.java
private void engineOverwriteInternal(File f) throws IOException { try {/*from w w w . ja v a2s . com*/ ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(f); boolean replaced = false; if (engineType != null && rootNode.get("engine_type") != null) { ((ObjectNode) rootNode).put("engine_type", Integer.parseInt(engineType)); replaced = true; } if (storageType != null && rootNode.get("storage_type") != null) { ((ObjectNode) rootNode).put("storage_type", Integer.parseInt(storageType)); replaced = true; } if (replaced) { objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.writeValue(f, rootNode); } } catch (JsonProcessingException ex) { logger.warn("cannot parse file {}", f); } }