/** * Logs an RPC response to the LOG file, producing valid JSON objects for client Operations. * * @param params The parameters received in the call. * @param methodName The name of the method invoked * @param call The string representation of the call * @param tag The tag that will be used to indicate this event in the log. * @param startTime The time that the call was initiated, in ms. * @param processingTime The duration that the call took to run, in ms. * @param qTime The duration that the call spent on the queue prior to being initiated, in ms. * @param responseSize The size in bytes of the response buffer. */ void logResponse(Object[] params, String methodName, String call, String tag, long startTime, int processingTime, int qTime, long responseSize) throws IOException { // for JSON encoding ObjectMapper mapper = new ObjectMapper(); // base information that is reported regardless of type of call Map<String, Object> responseInfo = new HashMap<String, Object>(); responseInfo.put("starttimems", startTime); responseInfo.put("processingtimems", processingTime); responseInfo.put("queuetimems", qTime); responseInfo.put("responsesize", responseSize); responseInfo.put("class", instance.getClass().getSimpleName()); responseInfo.put("method", methodName); responseInfo.put("call", call); /* * LOG.warn("(response" + tag + "): " + mapper.writeValueAsString(responseInfo)); */ }
@Test public void testScanningUnknownColumnJson() throws IOException, JAXBException { // Test scanning particular columns with limit. StringBuilder builder = new StringBuilder(); builder.append("/*"); builder.append("?"); builder.append(Constants.SCAN_COLUMN + "=a:test"); Response response = client.get("/" + TABLE + builder.toString(), Constants.MIMETYPE_JSON); assertEquals(200, response.getCode()); assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type")); ObjectMapper mapper = new JacksonProvider().locateMapper(CellSetModel.class, MediaType.APPLICATION_JSON_TYPE); CellSetModel model = mapper.readValue(response.getStream(), CellSetModel.class); int count = TestScannerResource.countCellSet(model); assertEquals(0, count); }
@Override public ReadAggregateResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException { int status = response.getStatusLine().getStatusCode(); switch (status) { case 200: HttpEntity entity = response.getEntity(); StringWriter writer = new StringWriter(); IOUtils.copy(entity.getContent(), writer, "UTF-8"); String json = writer.toString(); return mapper.readValue(json, ReadAggregateResult.class); case 400: throw new MalformedEventException(); case 401: throw new UnauthorizedAccessException(); default: throw new UnknownAPIException(response.getStatusLine().toString()); } }
private void updateAppTemplatesWhenDeployToJvmsChanged(final ResourceIdentifier resourceIdentifier, final String resourceName, final String previousMetaData, final String updatedMetaData) { try { ResourceTemplateMetaData oldMetaData = new ObjectMapper().readValue(previousMetaData, ResourceTemplateMetaData.class); ResourceTemplateMetaData newMetaData = new ObjectMapper().readValue(updatedMetaData, ResourceTemplateMetaData.class); boolean previousDeployToJvms = oldMetaData.getEntity().getDeployToJvms(); boolean newDeployToJvms = newMetaData.getEntity().getDeployToJvms(); if (previousDeployToJvms != newDeployToJvms) { Group group = groupPersistenceService.getGroup(resourceIdentifier.groupName); if (newDeployToJvms) { // deployToJvms was changed to true - need to create the JVM templates JpaGroupAppConfigTemplate appTemplate = resourceDao.getGroupLevelAppResource(resourceName, resourceIdentifier.webAppName, resourceIdentifier.groupName); newMetaData.setJsonData(updatedMetaData); createJvmTemplateFromAppResource(resourceIdentifier, appTemplate.getTemplateContent(), newMetaData, group); } else { // deployToJvms was to false - need to delete the JVM templates for (Jvm jvm : group.getJvms()) { resourceDao.deleteAppResource(resourceName, resourceIdentifier.webAppName, jvm.getJvmName()); } } } } catch (IOException ioe) { final String errorMsg = MessageFormat.format("Failed to parse meta data for war {0} in application {1} during an update of the meta data", resourceName, resourceIdentifier.webAppName); LOGGER.error(errorMsg, ioe); throw new GroupLevelAppResourceHandlerException(errorMsg); } }
/** * Creates a HTTP servlet response serializing the exception in it as JSON. * * @param response the servlet response * @param status the error code to set in the response * @param ex the exception to serialize in the response * @throws IOException thrown if there was an error while creating the * response */ public static void createServletExceptionResponse( HttpServletResponse response, int status, Throwable ex) throws IOException { response.setStatus(status); response.setContentType(APPLICATION_JSON_MIME); Map<String, Object> json = new LinkedHashMap<String, Object>(); json.put(ERROR_MESSAGE_JSON, getOneLineMessage(ex)); json.put(ERROR_EXCEPTION_JSON, ex.getClass().getSimpleName()); json.put(ERROR_CLASSNAME_JSON, ex.getClass().getName()); Map<String, Object> jsonResponse = new LinkedHashMap<String, Object>(); jsonResponse.put(ERROR_JSON, json); ObjectMapper jsonMapper = new ObjectMapper(); Writer writer = response.getWriter(); jsonMapper.writerWithDefaultPrettyPrinter().writeValue(writer, jsonResponse); writer.flush(); }
@Override public StatePair deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { ObjectMapper mapper = (ObjectMapper) parser.getCodec(); // set the state-pair object tree ObjectNode statePairObject = (ObjectNode) mapper.readTree(parser); Class<?> stateClass = null; try { stateClass = Class.forName(statePairObject.get("className").getTextValue().trim()); } catch (ClassNotFoundException cnfe) { throw new RuntimeException("Invalid classname!", cnfe); } String stateJsonString = statePairObject.get("state").toString(); State state = (State) mapper.readValue(stateJsonString, stateClass); return new StatePair(state); }
public DifficultyTestSuite(String json) throws IOException { ObjectMapper mapper = new ObjectMapper(); JavaType type = mapper.getTypeFactory(). constructMapType(HashMap.class, String.class, DifficultyTestCase.class); Map<String, DifficultyTestCase> caseMap = new ObjectMapper().readValue(json, type); for (Map.Entry<String, DifficultyTestCase> e : caseMap.entrySet()) { e.getValue().setName(e.getKey()); testCases.add(e.getValue()); } Collections.sort(testCases, new Comparator<DifficultyTestCase>() { @Override public int compare(DifficultyTestCase t1, DifficultyTestCase t2) { return t1.getName().compareTo(t2.getName()); } }); }
/** * Return the JSON formatted list of the files in the specified directory. * @param path a path specifies a directory to list * @return JSON formatted file list in the directory * @throws IOException if failed to serialize fileStatus to JSON. */ String listStatus(String path) throws IOException { StringBuilder sb = new StringBuilder(); ObjectMapper mapper = new ObjectMapper(); List<Map<String, Object>> fileStatusList = getFileStatusList(path); sb.append("{\"FileStatuses\":{\"FileStatus\":[\n"); int i = 0; for (Map<String, Object> fileStatusMap : fileStatusList) { if (i++ != 0) { sb.append(','); } sb.append(mapper.writeValueAsString(fileStatusMap)); } sb.append("\n]}}\n"); return sb.toString(); }
public static List<String> toXAttrNames(final Map<?, ?> json) throws IOException { if (json == null) { return null; } final String namesInJson = (String) json.get("XAttrNames"); ObjectReader reader = new ObjectMapper().reader(List.class); final List<Object> xattrs = reader.readValue(namesInJson); final List<String> names = Lists.newArrayListWithCapacity(json.keySet().size()); for (Object xattr : xattrs) { names.add((String) xattr); } return names; }
@Override public ProducedEventsResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException { int status = response.getStatusLine().getStatusCode(); switch (status) { case 200: HttpEntity entity = response.getEntity(); StringWriter writer = new StringWriter(); IOUtils.copy(entity.getContent(), writer, "UTF-8"); String json = writer.toString(); return mapper.readValue(json, ProducedEventsResult.class); case 400: throw new MalformedEventException(); case 401: throw new UnauthorizedAccessException(); default: throw new UnknownAPIException(response.getStatusLine().toString()); } }
@Test public void testValidateResponseJsonErrorUnknownException() throws IOException { Map<String, Object> json = new HashMap<String, Object>(); json.put(HttpExceptionUtils.ERROR_EXCEPTION_JSON, "FooException"); json.put(HttpExceptionUtils.ERROR_CLASSNAME_JSON, "foo.FooException"); json.put(HttpExceptionUtils.ERROR_MESSAGE_JSON, "EX"); Map<String, Object> response = new HashMap<String, Object>(); response.put(HttpExceptionUtils.ERROR_JSON, json); ObjectMapper jsonMapper = new ObjectMapper(); String msg = jsonMapper.writeValueAsString(response); InputStream is = new ByteArrayInputStream(msg.getBytes()); HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); Mockito.when(conn.getErrorStream()).thenReturn(is); Mockito.when(conn.getResponseMessage()).thenReturn("msg"); Mockito.when(conn.getResponseCode()).thenReturn( HttpURLConnection.HTTP_BAD_REQUEST); try { HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED); Assert.fail(); } catch (IOException ex) { Assert.assertTrue(ex.getMessage().contains("EX")); Assert.assertTrue(ex.getMessage().contains("foo.FooException")); } }
@Private public JsonNode countersToJSON(Counters counters) { ObjectMapper mapper = new ObjectMapper(); ArrayNode nodes = mapper.createArrayNode(); if (counters != null) { for (CounterGroup counterGroup : counters) { ObjectNode groupNode = nodes.addObject(); groupNode.put("NAME", counterGroup.getName()); groupNode.put("DISPLAY_NAME", counterGroup.getDisplayName()); ArrayNode countersNode = groupNode.putArray("COUNTERS"); for (Counter counter : counterGroup) { ObjectNode counterNode = countersNode.addObject(); counterNode.put("NAME", counter.getName()); counterNode.put("DISPLAY_NAME", counter.getDisplayName()); counterNode.put("VALUE", counter.getValue()); } } } return nodes; }
@Override public ReadCommitResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException { int status = response.getStatusLine().getStatusCode(); switch (status) { case 200: return new ReadCommitResult(true); case 400: throw new MalformedEventException(); case 401: throw new UnauthorizedAccessException(); default: throw new UnknownAPIException(response.getStatusLine().toString()); } }
public BigInteger getBalance(String address) throws IOException { String s = "https://"+url+"/api" + "?module=account" + "&action=balance" + "&address=" + address + "&tag=latest" + "&apikey="+apiKey; HttpHeaders headers = new HttpHeaders(); headers.set("User-Agent", options.getUserAgent()); ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); ObjectMapper objectMapper = new ObjectMapper(); ReturnSingleValue retVal = objectMapper.readValue(res.getBody(), ReturnSingleValue.class); return new BigInteger(retVal.result); }
static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream ) throws IOException { if (c.getContentLength() == 0) { return null; } final InputStream in = useErrorStream? c.getErrorStream(): c.getInputStream(); if (in == null) { throw new IOException("The " + (useErrorStream? "error": "input") + " stream is null."); } try { final String contentType = c.getContentType(); if (contentType != null) { final MediaType parsed = MediaType.valueOf(contentType); if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) { throw new IOException("Content-Type \"" + contentType + "\" is incompatible with \"" + MediaType.APPLICATION_JSON + "\" (parsed=\"" + parsed + "\")"); } } ObjectMapper mapper = new ObjectMapper(); return mapper.reader(Map.class).readValue(in); } finally { in.close(); } }
/** * Can process up to 20 contracts */ public BigInteger get20Balances(List<String> contract) throws IOException { String addresses = String.join(",", contract); String s = "https://"+url+"/api" + "?module=account" + "&action=balancemulti" + "&address=" + addresses + "&tag=latest" + "&apikey="+apiKey; HttpHeaders headers = new HttpHeaders(); headers.set("User-Agent", options.getUserAgent()); ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class); ObjectMapper objectMapper = new ObjectMapper(); ReturnValues retVal = objectMapper.readValue(res.getBody(), ReturnValues.class); BigInteger result = BigInteger.ZERO; for(ReturnValues.Result res1: retVal.result) { result = result.add(new BigInteger(res1.balance)); } return result; }
@Override public ReadAggregatesResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException { int status = response.getStatusLine().getStatusCode(); switch (status) { case 200: HttpEntity entity = response.getEntity(); StringWriter writer = new StringWriter(); IOUtils.copy(entity.getContent(), writer, "UTF-8"); String json = writer.toString(); return mapper.readValue(json, ReadAggregatesResult.class); case 400: throw new MalformedEventException(); case 401: throw new UnauthorizedAccessException(); default: throw new UnknownAPIException(response.getStatusLine().toString()); } }
public String search(String query) { try { String url = "?text=" + Utility.urlEncode(query) + "&confidence=" + confidence; HttpGet httpGet = new HttpGet(URL + url); httpGet.addHeader("Accept", "application/json"); HttpResponse response = client.execute(httpGet); // Error Scenario if(response.getStatusLine().getStatusCode() >= 400) { logger.error("Spotlight Service could not answer due to: " + response.getStatusLine()); return null; } else { String entities = EntityUtils.toString(response.getEntity()); JsonNode entity = new ObjectMapper().readTree(entities).get("Resources").get(0); return entity.get("@URI").getTextValue(); } } catch (Exception e) { e.printStackTrace(); } return null; }
/** * Gets the State of the Tweet by checking the InputStream. * For a sample Bing Maps API response, please check the snippet at the end of this file. * * @param inputStream Bing Maps API response. * @return State of the Tweet as got from Bing Maps API reponse. */ @SuppressWarnings("unchecked") private final static Optional<String> getStateFromJSONResponse(InputStream inputStream) { final ObjectMapper mapper = new ObjectMapper(); try { //final Map<String,Object> bingResponse = (Map<String, Object>) mapper.readValue(new File("C:/BingMaps_JSON_Response.json"), Map.class); final Map<String,Object> bingResponse = (Map<String, Object>) mapper.readValue(inputStream, Map.class); if(200 == Integer.parseInt(String.valueOf(bingResponse.get("statusCode")))) { final List<Map<String, Object>> resourceSets = (List<Map<String, Object>>) bingResponse.get("resourceSets"); if(resourceSets != null && resourceSets.size() > 0){ final List<Map<String, Object>> resources = (List<Map<String, Object>>) resourceSets.get(0).get("resources"); if(resources != null && resources.size() > 0){ final Map<String, Object> address = (Map<String, Object>) resources.get(0).get("address"); LOGGER.debug("State==>{}", address.get("adminDistrict")); return Optional.of((String) address.get("adminDistrict")); } } } } catch (final IOException ioException) { LOGGER.error(ioException.getMessage(), ioException); ioException.printStackTrace(); } return Optional.absent(); }
/** * manifest_jsonのschemaの指定がない場合falseが返却されること. * @throws IOException IOException */ @SuppressWarnings("unchecked") @Test public void manifest_jsonのschemaの指定がない場合falseが返却されること() throws IOException { JsonFactory f = new JsonFactory(); JSONObject json = new JSONObject(); json.put("bar_version", "1"); json.put("box_version", "1"); json.put("DefaultPath", "boxName"); JsonParser jp = f.createJsonParser(json.toJSONString()); ObjectMapper mapper = new ObjectMapper(); jp.nextToken(); JSONManifest manifest = mapper.readValue(jp, JSONManifest.class); assertFalse(manifest.checkSchema()); }
private static StringWriter buildStringWriter(List<Node> nodes, List<Edge> edges, Map<EVMEnvironment, SymExecutor> executions) throws ReportException { VelocityEngine velocityEngine = new VelocityEngine(); Properties p = new Properties(); p.setProperty("resource.loader", "class"); p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); velocityEngine.init(p); Template template = velocityEngine.getTemplate(TEMPLATE_FILE); VelocityContext velocityContext = new VelocityContext(); ObjectMapper objectMapper = new ObjectMapper(); try { velocityContext.put("nodes", objectMapper.writeValueAsString(nodes)); velocityContext.put("edges", objectMapper.writeValueAsString(edges)); velocityContext.put("executions", executions); } catch (IOException e) { logger.error("Error building the report: " + e); throw new ReportException("Failed creating ReportItem"); } StringWriter stringWriter = new StringWriter(); template.merge(velocityContext, stringWriter); return stringWriter; }
@Override public Object execute(List<ExpressionData<?>> dataList, Context context,Cell currentCell){ if(dataList.size()!=2){ return null; } String obj = buildData(dataList.get(0)); String property=buildData(dataList.get(1)); if(obj==null || property==null || obj.equals("") || property.equals("")){ return null; } ObjectMapper mapper=new ObjectMapper(); try{ Map<?,?> map=mapper.readValue(obj, HashMap.class); return Utils.getProperty(map, property); }catch(Exception ex){ throw new ReportException(ex); } }
@Override protected void configure() { // Bind core implementations of guacamole-ext classes bind(AuthenticationProvider.class).toInstance(authProvider); bind(Environment.class).toInstance(environment); // Bind services bind(ConfigurationService.class); bind(UserDataService.class); // Bind singleton ObjectMapper for JSON serialization/deserialization bind(ObjectMapper.class).in(Scopes.SINGLETON); // Bind singleton Jersey REST client bind(Client.class).toInstance(Client.create(CLIENT_CONFIG)); }
@SuppressWarnings({ "unchecked", "rawtypes" }) private List<GeneralEntity> buildList(String value){ try { List<GeneralEntity> result=new ArrayList<GeneralEntity>(); ObjectMapper mapper=new ObjectMapper(); Map<String,Object> map=mapper.readValue(value, HashMap.class); if(map.containsKey("rows")){ List<Object> list=(List<Object>)map.get("rows"); for(Object obj:list){ if(obj instanceof Map){ GeneralEntity entity=new GeneralEntity((String)map.get("type")); entity.putAll((Map)obj); result.add(entity); } } return result; }else{ return null; } } catch (Exception e) { throw new RuleException(e); } }
@SuppressWarnings({ "unchecked", "rawtypes" }) private Set<GeneralEntity> buildSet(String value){ try { Set<GeneralEntity> result=new HashSet<GeneralEntity>(); ObjectMapper mapper=new ObjectMapper(); Map<String,Object> map=mapper.readValue(value, HashMap.class); if(map.containsKey("rows")){ List<Object> list=(List<Object>)map.get("rows"); for(Object obj:list){ if(obj instanceof Map){ GeneralEntity entity=new GeneralEntity((String)map.get("type")); entity.putAll((Map)obj); result.add(entity); } } return result; }else{ return null; } } catch (Exception e) { throw new RuleException(e); } }
/** * リクエストボディを解析してEventオブジェクトを取得する. * @param reader Http入力ストリーム * @return 解析したEventオブジェクト */ protected JSONEvent getRequestBody(final Reader reader) { JSONEvent event = null; JsonParser jp = null; ObjectMapper mapper = new ObjectMapper(); JsonFactory f = new JsonFactory(); try { jp = f.createJsonParser(reader); JsonToken token = jp.nextToken(); // JSONルート要素("{") if (token == JsonToken.START_OBJECT) { event = mapper.readValue(jp, JSONEvent.class); } else { throw PersoniumCoreException.Event.JSON_PARSE_ERROR; } } catch (IOException e) { throw PersoniumCoreException.Event.JSON_PARSE_ERROR; } return event; }
private void write(DataOutput out) throws IOException { // This is just a JSON experiment System.out.println("Dumping the StatePool's in JSON format."); ObjectMapper outMapper = new ObjectMapper(); outMapper.configure( SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true); // define a module SimpleModule module = new SimpleModule("State Serializer", new Version(0, 1, 1, "FINAL")); // add the state serializer //module.addSerializer(State.class, new StateSerializer()); // register the module with the object-mapper outMapper.registerModule(module); JsonFactory outFactory = outMapper.getJsonFactory(); JsonGenerator jGen = outFactory.createJsonGenerator((DataOutputStream)out, JsonEncoding.UTF8); jGen.useDefaultPrettyPrinter(); jGen.writeObject(this); jGen.close(); }
@Override public boolean signIn(String u, String p) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ObjectMapper mapper=ObjectMapperPool.getMapper(); String json=""; try { json = mapper.writeValueAsString(new LoginRequest(u, p, fingerPrint.getFingerPrint())); HttpEntity<String> entity = new HttpEntity<String>(json, headers); ResponseEntity<String> response=restTemplate.postForEntity(serverPath.concat(Constants.SIGN_IN_SUFFIX), entity, String.class); LoginResponse resp=mapper.readValue(response.getBody(), LoginResponse.class); logger.debug("Got login response {}",resp.getResult()); return resp.getResult(); } catch (Exception e) { logger.error("Parse exception", e); } return false; }
@Override public boolean createNewUser(String u, String p) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ObjectMapper mapper=ObjectMapperPool.getMapper(); String json=""; try { json = mapper.writeValueAsString(new LoginRequest(u, p, fingerPrint.getFingerPrint())); HttpEntity<String> entity = new HttpEntity<String>(json, headers); ResponseEntity<String> response=restTemplate.postForEntity(serverPath.concat(Constants.CREATE_USER_SUFFIX), entity, String.class); CreateUserResponse resp=mapper.readValue(response.getBody(), CreateUserResponse.class); logger.debug("Got create user response {}",resp.getStatus()); return resp.isResult(); } catch (Exception e) { logger.error("Parse exception", e); } return false; }
@Override public TopicRecord deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); String topic = node.get("topic").asText(); long partition = node.get("partition").asLong(); long offset = node.get("offset").asLong(); long timestamp = node.get("timestamp").asLong(); String key = null; if (node.has("key")) { key = node.get("key").asText(); } Map<Object, Object> value = new ObjectMapper().readValue(node.get("value").toString(), Map.class); return new TopicRecord(topic, key, partition, offset, timestamp, value); }
/** * manifest_jsonのschema値がURL形式でない場合falseが返却されること. * @throws IOException IOException */ @SuppressWarnings("unchecked") @Test public void manifest_jsonのschema値がURL形式でない場合falseが返却されること() throws IOException { JsonFactory f = new JsonFactory(); JSONObject json = new JSONObject(); json.put("bar_version", "1"); json.put("box_version", "1"); json.put("DefaultPath", "boxName"); json.put("schema", "test"); JsonParser jp = f.createJsonParser(json.toJSONString()); ObjectMapper mapper = new ObjectMapper(); jp.nextToken(); JSONManifest manifest = mapper.readValue(jp, JSONManifest.class); assertFalse(manifest.checkSchema()); }
@Test public void testDeserializeJsonCreateJvm() throws Exception { final InputStream in = this.getClass().getResourceAsStream("/json-create-jvm-data.json"); final String jsonData = IOUtils.toString(in, Charset.defaultCharset()); final ObjectMapper mapper = new ObjectMapper(); final JsonCreateJvm jsonCreateJvm = mapper.readValue(jsonData, JsonCreateJvm.class); assertEquals("my-jvm", jsonCreateJvm.getJvmName()); assertEquals("some-host", jsonCreateJvm.getHostName()); assertEquals("jwala", jsonCreateJvm.getUserName()); assertEquals("/manager", jsonCreateJvm.getStatusPath()); assertEquals("1", jsonCreateJvm.getJdkMediaId()); assertTrue(StringUtils.isNotEmpty(jsonCreateJvm.getEncryptedPassword())); assertNotEquals("password", jsonCreateJvm.getEncryptedPassword()); assertEquals("8893", jsonCreateJvm.getAjpPort()); assertEquals("8889", jsonCreateJvm.getHttpPort()); assertEquals("8890", jsonCreateJvm.getHttpsPort()); assertEquals("8891", jsonCreateJvm.getRedirectPort()); assertEquals("8892", jsonCreateJvm.getShutdownPort()); assertEquals("1", jsonCreateJvm.getGroupIds().get(0).getGroupId()); }
@Override // FSNamesystemMBean public String getTopUserOpCounts() { if (!topConf.isEnabled) { return null; } Date now = new Date(); final List<RollingWindowManager.TopWindow> topWindows = topMetrics.getTopWindows(); Map<String, Object> topMap = new TreeMap<String, Object>(); topMap.put("windows", topWindows); topMap.put("timestamp", DFSUtil.dateToIso8601String(now)); ObjectMapper mapper = new ObjectMapper(); try { return mapper.writeValueAsString(topMap); } catch (IOException e) { LOG.warn("Failed to fetch TopUser metrics", e); } return null; }
@PUT @Path("/validate") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response userValidation(User userData) { try { int flag = 0; String emailRcvd = ""; final ObjectNode node = new ObjectMapper().readValue(userData.toString(), ObjectNode.class); if (node.has("email")) { emailRcvd = node.get("email").toString().replace("\"", "").trim(); } ResultSet rs = dbobj.openConnection("select email from user"); while (rs.next()) { String userEmail = rs.getString("email"); if (emailRcvd.equals(userEmail)) { flag = 1; break; } } if (flag == 1) { resp.put("response", "false"); return Response.ok(resp.toJSONString()).build(); } dbobj.closeConnection(rs); } catch (SQLException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } resp.put("response", "true"); return Response.ok(resp.toJSONString()).build(); }
/** * manifest.jsonのバリデート. * @param jp Jsonパーサー * @param mapper ObjectMapper * @return JSONManifestオブジェクト * @throws IOException データの読み込みに失敗した場合 */ protected JSONManifest manifestJsonValidate(JsonParser jp, ObjectMapper mapper) throws IOException { // TODO BARファイルのバージョンチェック JSONManifest manifest = null; try { manifest = mapper.readValue(jp, JSONManifest.class); } catch (UnrecognizedPropertyException ex) { throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params( "manifest.json unrecognized property"); } if (manifest.getBarVersion() == null) { throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params("manifest.json#barVersion"); } if (manifest.getBoxVersion() == null) { throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params("manifest.json#boxVersion"); } if (manifest.getDefaultPath() == null) { throw PersoniumCoreException.BarInstall.JSON_FILE_FORMAT_ERROR.params("manifest.json#DefaultPath"); } return manifest; }
public static void main(String[] args) throws IOException { final Configuration conf = new Configuration(); final FileSystem lfs = FileSystem.getLocal(conf); for (String arg : args) { Path filePath = new Path(arg).makeQualified(lfs); String fileName = filePath.getName(); if (fileName.startsWith("input")) { LoggedDiscreteCDF newResult = histogramFileToCDF(filePath, lfs); String testName = fileName.substring("input".length()); Path goldFilePath = new Path(filePath.getParent(), "gold"+testName); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getJsonFactory(); FSDataOutputStream ostream = lfs.create(goldFilePath, true); JsonGenerator gen = factory.createJsonGenerator(ostream, JsonEncoding.UTF8); gen.useDefaultPrettyPrinter(); gen.writeObject(newResult); gen.close(); } else { System.err.println("Input file not started with \"input\". File "+fileName+" skipped."); } } }
public String getSchedulingDecisionSummary() { Map<Object, Integer> decisions = scheduleCacheRef.get(); if (decisions == null) { return "{}"; } else { try { ObjectMapper om = new ObjectMapper(); return om.writeValueAsString(decisions); } catch (Exception e) { return "Error: " + e.getMessage(); } } }
public BlockTestSuite(String json) throws IOException { ObjectMapper mapper = new ObjectMapper(); JavaType type = mapper.getTypeFactory(). constructMapType(HashMap.class, String.class, BlockTestCase.class); testCases = new ObjectMapper().readValue(json, type); }
private static String mapToJson(Map map){ ObjectMapper mapperObj = new ObjectMapper(); String jsonResp = ""; try { jsonResp = mapperObj.writeValueAsString(map); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonResp; }