public String formMessage(String content) { try { JsonObject contentObj = new JsonParser().parse(content).getAsJsonObject(); int userId = contentObj.get("uid").getAsInt(); String datetime = contentObj.get("datetime").getAsString(); SimpleDateFormat insdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); SimpleDateFormat outsdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String parsedDatetime = outsdf.format(insdf.parse(datetime)); String chatContent = contentObj.get("content").getAsString(); String username = userDao.getUserById(userId).getUsername(); String avatar = userDao.getUserById(userId).getAvatar(); JsonObject messageJson = new JsonObject(); messageJson.addProperty("uid", userId); messageJson.addProperty("username", username); messageJson.addProperty("datetime", parsedDatetime); messageJson.addProperty("avatar", avatar); messageJson.addProperty("content", chatContent); return messageJson.toString(); } catch (ParseException e) { e.printStackTrace(); return "error"; } }
public static Mat matFromJson(String json){ JsonParser parser = new JsonParser(); JsonObject JsonObject = parser.parse(json).getAsJsonObject(); int rows = JsonObject.get("rows").getAsInt(); int cols = JsonObject.get("cols").getAsInt(); int type = JsonObject.get("type").getAsInt(); String dataString = JsonObject.get("data").getAsString(); byte[] data = DatatypeConverter.parseBase64Binary(dataString); // byte[] data = Base64.decode(dataString.getBytes(), Base64.DEFAULT); Mat mat = new Mat(rows, cols, type); mat.put(0, 0, data); return mat; }
@Override public String post(final HttpServletRequest req, final HttpServletResponse res) { try { final String payload = req.getParameter("payload"); final JsonParser jsonParser = new JsonParser(); final JsonObject json = jsonParser.parse(payload).getAsJsonObject(); final Map<String, String[]> params = req.getParameterMap(); slackReceiveHandler.handleAction(json, params); } catch (final Exception e) { handleException(e); } return ""; }
public File downloadNote(int noteId, String type, String leftPath)throws IOException, DocumentException { Note note = noteDao.getNoteById(noteId); String currentVersion = note.getHistory().get(note.getVersionPointer()); JsonObject obj = new JsonParser().parse(currentVersion).getAsJsonObject(); String content = obj.get("content").getAsString(); String htmlPath = leftPath + "htmlTemp.html"; File file = new File(htmlPath); file.createNewFile(); FileWriter writer = new FileWriter(file); writer.write("<body>" + content + "</body>"); writer.close(); if(type.equals("pdf")) { String pdfPath = leftPath + "pdfTemp.pdf"; File pdfFile = new File(pdfPath); exportUtil.htmlToPdf(htmlPath, pdfFile); file.delete(); file = pdfFile; } //default html return file; }
public static Weather convertJSONToWeatherObj(String jsonString) { Weather weatherObj = new Weather(); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(jsonString).getAsJsonObject(); weatherObj.setTemperature(new Temperature(Temperature.Unit.KELVIN, Double.parseDouble(json.getAsJsonObject("main").get("temp").toString()))); for (int index = 0; index < json.getAsJsonArray("weather").size(); index++) { JsonObject object = json.getAsJsonArray("weather").get(index).getAsJsonObject(); weatherObj.getCondition().add( weatherCodes.getConditionFromCode(Integer.parseInt(object.get("id").toString()))); weatherObj.setIcon(fileLoad.loadImageFromService(object.get("icon").getAsString())); } return weatherObj; }
public Configuration(final File file) { this.file = file; String cont = null; this.jsonParser = new JsonParser(); try { if (file.exists()) { cont = new BufferedReader(new FileReader(this.file)).lines().collect(Collectors.joining("\n")); //cont = IOUtils.toString(new BufferedInputStream(new FileInputStream(this.file)), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } if (cont == null || cont.equals("")) { cont = "{}"; } json = jsonParser.parse(cont).getAsJsonObject(); }
@FXML private void actionLoad(ActionEvent event) { fileChooser.setTitle("Load Config"); File file = fileChooser.showOpenDialog(paneConfig.getScene().getWindow()); try { String config = FileUtils.readFileToString(file, "UTF-8"); JsonElement json = new JsonParser().parse(config); wrapper.configure(json, null, null); } catch (IOException ex) { LOGGER.error("Failed to read file", ex); Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("failed to read file"); alert.setContentText(ex.getLocalizedMessage()); alert.showAndWait(); } }
private void assertFileInCache (File file,String key) throws IOException { InputStream in = new FileInputStream(file); try { Reader reader = new InputStreamReader(in); String text = CharStreams.toString(reader); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(text); JsonObject jsonCache = je.getAsJsonObject(); JsonElement elt = jsonCache.get(key); JsonObject generatedObj = elt.getAsJsonObject(); boolean generated = generatedObj.get("generated").getAsBoolean(); assertTrue("Test not generated", generated); } finally { if (in!=null) in.close(); } }
@Test public void testSerialization() { Gson gson = getGSON(getFactory(t -> "foo", emptyList(), emptyList())); SubTypeA typeA = new SubTypeA(); typeA.foo = 1; typeA.bar = "t1"; typeA.baz = "t2"; JsonElement actual = gson.toJsonTree(typeA, new TypeToken<Base>() { }.getType()); JsonElement expected = new JsonParser().parse(makeJSON(1, "t1", "t2")); Assert.assertEquals(actual, expected); SubTypeB typeB = new SubTypeB(); typeB.foo = 2; typeB.bar = "t2"; typeB.qux = asList("a", "b"); actual = gson.toJsonTree(typeB, new TypeToken<Base>() { }.getType()); expected = new JsonParser().parse(makeJSON(2, "t2", asList("a", "b"))); Assert.assertEquals(actual, expected); }
/** * Test train string. */ @Test @Ignore // only run train test if necessary. This is an expensive process. public void testTrainString() { if (checkConnection()) { JsonParser parser = new JsonParser(); Object obj; try { obj = parser.parse(new FileReader("src/test/resources/training.json")); JsonObject jsonObject = (JsonObject) obj; System.out.println(jsonObject.toString()); RasaService.sendTrainRequest(jsonObject.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } checkConnection(); assert (true); }
public File downloadNotebook(int notebookId, String type, String leftPath) throws IOException,DocumentException{ File tempDir = new File(leftPath + "tempDir"); String tempPath = leftPath + "tempDir/"; tempDir.mkdirs(); ArrayList<Integer> notes = notebookDao.getNotebookById(notebookId).getNotes(); for(int noteId : notes){ Note note = noteDao.getNoteById(noteId); String currentVersion = note.getHistory().get(note.getVersionPointer()); JsonObject obj = new JsonParser().parse(currentVersion).getAsJsonObject(); String content = obj.get("content").getAsString(); String htmlPath = tempPath + noteId +".html"; File file = new File(htmlPath); file.createNewFile(); FileWriter writer = new FileWriter(file); writer.write("<body>" + content + "</body>"); writer.close(); if(type.equals("pdf")) { String pdfPath = tempPath + noteId +".pdf"; File pdfFile = new File(pdfPath); exportUtil.htmlToPdf(htmlPath, pdfFile); file.delete(); } } return exportUtil.compressExe(tempDir, leftPath + "temp.zip"); }
/** * 根据code获取微信token和openid * * @param code * @return */ public static JsonObject getWeiXinMessage(String code) throws Exception { JsonParser parser = new JsonParser(); logger.info("wechat code:" + code); String toGetToken = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=" + SSOCommon.weixinAppKey + "&secret=" + SSOCommon.weixinAppSecret + "&code=" + code + "&grant_type=authorization_code"; logger.info(toGetToken); String tokeContent = HttpHelper.getInstance().get(toGetToken); //access token logger.info(tokeContent); JsonObject object = null; //取得token和openid if (tokeContent != null) { object = parser.parse(tokeContent).getAsJsonObject(); if (object.get("errcode") != null) { throw new Exception("访问微信出现异常"); } } return object; }
public String recognizeImagePath(String imageUrl) throws Exception { String filePath = urltoImagePath(imageUrl); HashMap<String, String> options = new HashMap<>(); options.put("detect_direction", "true"); options.put("probability", "true"); String str = client.basicGeneral(filePath, options).toString(); logger.info("返回的文本:" + str); JsonParser parser = new JsonParser(); JsonObject object = parser.parse(str).getAsJsonObject(); try { return object.get("words_result").getAsJsonArray().get(0).getAsJsonObject().get("words").getAsString(); } catch (Exception e) { logger.error("", e); throw new Exception(); } finally { FileUtils.deleteQuietly(new File(filePath)); } }
public static Collection<String> validate(String json, Collection<String> requiredFields) throws InvalidJson { if (json == null) { throw new InvalidJson("Null JSON object"); } try { ArrayList<String> missing = new ArrayList<>(); JsonParser parser = new JsonParser(); JsonObject root = parser.parse(json).getAsJsonObject(); for (String field : requiredFields) { if (!root.has(field)) { missing.add(field); } } return missing; } catch (JsonSyntaxException e) { throw new InvalidJson("Malformed JSON: " + json); } }
@Override public void run() { String json = ""; try { Scanner sc = new Scanner(new URL(streamLink).openStream()); StringBuilder sb = new StringBuilder(); while(sc.hasNextLine()) sb.append(sc.nextLine()); json = sb.toString(); } catch (Exception e) { e.printStackTrace(); } System.out.println(json); JsonObject jsonData = new JsonParser().parse(json).getAsJsonObject(); JsonObject stream = jsonData.get("stream").getAsJsonObject(); Twitchy.isLive = stream != null; if(stream != null) { Twitchy.streamGame = getJsonString(stream.get("game"), ""); Twitchy.streamViewers = getJsonInt(stream.get("viewers"), 0); Twitchy.streamTitle = getJsonString(stream.get("channel").getAsJsonObject().get("status"), ""); } }
/** * Gets the test data. * * @param <T> the generic type * @param testName the test name * @param cls the cls * @return the test data */ public static <T> List<T> getJsonData(String testName, Class<T> cls) { List<T> list = new ArrayList<T>(); try { final String profile = getCurrentProfile(); final JsonElement jsonData = new JsonParser().parse(new FileReader("src/test/resources/test-data-"+profile+".json")); final JsonElement dataSet = jsonData.getAsJsonObject().get("dataset-" + testName); Gson gson = new Gson(); JsonArray arry = dataSet.getAsJsonArray(); for (JsonElement jsonElement : arry) { list.add(gson.fromJson(jsonElement, cls)); } } catch (Exception e) { e.printStackTrace(); } return list; }
private static boolean isValidJSON(String input) { if (StringUtils.isBlank(input)) { logger.warn("Parsing empty json string to protobuf is deprecated and will be removed in " + "the next major release"); return false; } if (!input.startsWith("{")) { logger.warn("Parsing json string that does not start with { is deprecated and will be " + "removed in the next major release"); return false; } try { new JsonParser().parse(input); } catch (JsonParseException ex) { return false; } return true; }
public JsonObject readFileAsJsonObject(GcsFilename file) throws IOException { GcsFileMetadata metadata = gcsService.getMetadata(file); if (metadata == null) { if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Development) { // In the development server, try to fetch files on cloud storage via HTTP Logger.getAnonymousLogger().info("fetching "+file.getObjectName()+" at "+Config.CLOUD_STORAGE_BASE_URL+file.getObjectName()); return RemoteJsonHelper.fetchJsonFromPublicURL(Config.CLOUD_STORAGE_BASE_URL+file.getObjectName()); } return null; } GcsInputChannel readChannel = null; try { readChannel = gcsService.openReadChannel(file, 0); JsonElement element = new JsonParser().parse(Channels.newReader(readChannel, DEFAULT_CHARSET_NAME)); return element.getAsJsonObject(); } finally { if (readChannel != null) { readChannel.close(); } } }
public String parseAddress(String result){ JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(result); JsonElement jsonCode = json.get("status"); String code = jsonCode.getAsString(); if(! (code.equals("OK"))){ return null; } JsonArray jsonArray = json.getAsJsonArray("results"); JsonElement elm = jsonArray.get(0); JsonObject obj = elm.getAsJsonObject(); JsonElement ob2 = obj.get("formatted_address"); return ob2.getAsString(); }
@Test public void double_deep() { String template = "{ \"a\" : { \"b\": \"{{value}}\"}, \"c\": { \"b\": \"{{value}}\"}}"; JsonObject document = (JsonObject) new JsonParser().parse(template); Map<String, String> paths = JsonUtil.getJsonPathsForTemplating(document); assertEquals(2, paths.size()); Object a = paths.get("$.a.b"); assertNotNull(a); assertEquals("{{value}}", a.toString()); Object b = paths.get("$.c.b"); assertNotNull(b); assertEquals("{{value}}", a.toString()); }
private boolean pushBizLogToServer(String url) { String postData = fetchQueue(sendBizLogQueue, 2); if (postData.trim().length() > 0) { log.info("fetch biz size:" + postData.trim().length()); String retString = postHttp(url, postData); if (retString.equals("")) { return false; } try { JsonParser jsonParser = new JsonParser(); JsonObject retObj = jsonParser.parse(retString).getAsJsonObject(); if (retObj.get("code").getAsInt() != 0) { log.error("bizlog:" + retString); } else { log.info("bizlog:" + retString); return true; } } catch (Exception e) { e.printStackTrace(); log.error(e.getMessage()); } } return false; }
@OnWebSocketMessage public void onMessage(String msg) { JsonObject messageObject = new JsonParser().parse(msg).getAsJsonObject(); long typeId = messageObject.get("TypeID").getAsLong(); if(typeId == TYPE_ID_MESSAGE_RECEIVE) { JsonObject bodyObject = messageObject.getAsJsonObject("Body"); System.out.println(bodyObject.get("Body").getAsString()); if(!bodyObject.get("ClientID").getAsString().equals(messenger.getClientId())) { for(TwitchMessengerListener listener : messenger.getListeners()) { listener.onMessage(messenger .getServer(bodyObject.get("ServerID").getAsString()) .getConversation(bodyObject.get("ConversationID").getAsString()), bodyObject.get("Body").getAsString()); } } } else if(typeId == TYPE_ID_SIGNAL_PING) { // got pong } else if(typeId == TYPE_ID_SERVER_INFO) { // got server infos } else if(typeId == TYPE_ID_FRIENDS_STATUS_CHANGE) { // got friends status change events } else { System.out.println(String.format("Unhandled Web Socket Packet: %s, Message: %s", typeId, msg)); } }
public static JsonObject convertFileToJson(String filename) { try { BufferedReader br = new BufferedReader(new FileReader(filename)); if (br.readLine() == null) { return null; } return new JsonParser().parse(new FileReader(filename)).getAsJsonObject(); } catch (Exception ex) { ex.printStackTrace(); return null; } }
@Override public <T> T process(BittrexRequest request, Class<T> clazz) { LOG.debug(String.format("Processing request for %s", request.getUri().toString())); try(CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { final HttpRequestBase getRequest = addHeadersToRequest(request.getMethod() == RequestMethod.GET ? new HttpGet() : new HttpPost(), request); final HttpResponse httpResponse = httpClient.execute(getRequest); LOG.debug(String.format("Request has processed - STATUS: %s", httpResponse.getStatusLine())); final JsonObject element = (JsonObject) new JsonParser().parse(IOUtils.toString(httpResponse.getEntity().getContent())); // on success if(element.get("success").getAsBoolean()) { JsonElement jsonElement = element.get("result"); LOG.debug(String.format("Trying to parse result to an instance of %s", clazz.getName())); return gson.fromJson(jsonElement, clazz); } else { LOG.debug("Request was not successful"); errorHandler.handle(element.get("message").getAsString()); } } catch (IOException e) { LOG.error(String.format("Failed to execute Response for %s", request.getUri().toString()), e); } return null; }
public ZippedResourcePack(File file) { if (!file.exists()) { throw new IllegalArgumentException(Server.getInstance().getLanguage() .translateString("nukkit.resources.zip.not-found", file.getName())); } this.file = file; try (ZipFile zip = new ZipFile(file)) { ZipEntry entry = zip.getEntry("manifest.json"); if (entry == null) { throw new IllegalArgumentException(Server.getInstance().getLanguage() .translateString("nukkit.resources.zip.no-manifest")); } else { this.manifest = new JsonParser() .parse(new InputStreamReader(zip.getInputStream(entry), StandardCharsets.UTF_8)) .getAsJsonObject(); } } catch (IOException e) { Server.getInstance().getLogger().logException(e); } if (!this.verifyManifest()) { throw new IllegalArgumentException(Server.getInstance().getLanguage() .translateString("nukkit.resources.zip.invalid-manifest")); } }
@RequestMapping(value = "/log/bizlog/put", method = RequestMethod.POST) @ResponseBody public ResponseJson appendLog(@RequestParam(value = "contents", required = false) String contents) { ResponseJson result = new ResponseJson(); if (contents == null || contents.length() == 0) { result.setCode(401); result.setMsg("Plasee set the contents paramter!"); return result; } //split the json to by \n String[] contentslist = contents.split("\n"); if (contentslist.length <= 0) { result.setCode(405); result.setMsg("contents paramter format Wrong!"); return result; } for (int i = 0; i < contentslist.length; i++) { String jsonstr = contentslist[i].trim(); JsonParser valueParse = new JsonParser(); if (jsonstr.length() == 0) { continue; } try { JsonArray valueArr = (JsonArray) valueParse.parse(jsonstr); bizLogProcessor.insertDataQueue(valueArr); } catch (Exception e) { //e.printStackTrace(); log.error("parser json wrong:" + jsonstr); } } return result; }
@Test public void versionTest() throws Exception { String parentDirectory = Paths.get(System.getProperty("user.dir"), "src", "main", "resources", "edu", "mit", "ll", "pace", "test", "encryption", "VersioningIT").toString(); JsonParser parser = new JsonParser(); JsonArray versions = parser.parse(new FileReader(Paths.get(parentDirectory, "config.json").toFile())).getAsJsonObject().getAsJsonArray("versions"); for (JsonElement versionElement : versions) { testVersion(Paths.get(parentDirectory, versionElement.getAsJsonPrimitive().getAsString()).toFile()); } }
public static List<Forecast> convertJSONToForecastObjs(String jsonString) { List<Forecast> forecasts = new ArrayList<>(); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(jsonString).getAsJsonObject(); for (int index = 0; index < json.getAsJsonArray("list").size(); index++) { JsonObject forecastsArray = json.getAsJsonArray("list").get(index).getAsJsonObject(); List<Weather.WeatherCondition> conditions = new ArrayList<>(); Image weatherIcon = null; for (int conditionsIndex = 0; conditionsIndex < forecastsArray.getAsJsonArray("weather").size(); conditionsIndex++) { JsonObject weatherConditionArray = forecastsArray.getAsJsonArray("weather").get(conditionsIndex).getAsJsonObject(); conditions.add(weatherCodes.getConditionFromCode(Integer.parseInt(weatherConditionArray.get("id").toString()))); weatherIcon = fileLoad.loadImageFromService(weatherConditionArray.get("icon").getAsString()); } forecasts.add(new Forecast( new Weather(conditions, new Temperature(Temperature.Unit.KELVIN, Double.parseDouble(forecastsArray.get("main").getAsJsonObject().get("temp").toString())), weatherIcon), new Date(forecastsArray.get("dt").getAsLong() * 1000L))); } return forecasts; }
@Override public ModelFluid process(ImmutableMap<String, String> customData) { if(!customData.containsKey("fluid")) return this; String fluidStr = customData.get("fluid"); JsonElement e = new JsonParser().parse(fluidStr); String fluid = e.getAsString(); if(!FluidRegistry.isFluidRegistered(fluid)) { FMLLog.severe("fluid '%s' not found", fluid); return WATER; } return new ModelFluid(FluidRegistry.getFluid(fluid)); }
/** * * @param jsonFile * @return * @throws IOException */ public static EasyJson parse(File jsonFile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(jsonFile)); try { JsonElement jsonElt = new JsonParser().parse(reader); return new EasyJson(jsonElt); } finally { reader.close(); } }
public boolean sendSwitch(OnOffType command) throws IOException { String jsonData = sendCommand(command == ON ? Command.SWITCH_ON : Command.SWITCH_OFF); if (jsonData.length() > 0) { JsonObject jo = new JsonParser().parse(jsonData).getAsJsonObject(); int errorCode = jo.get("system").getAsJsonObject().get("set_relay_state").getAsJsonObject().get("err_code") .getAsInt(); return errorCode == 0; } return false; }
public static MatOfKeyPoint jsonToKeypoints(String json){ MatOfKeyPoint result = new MatOfKeyPoint(); JsonParser parser = new JsonParser(); JsonArray jsonArr = parser.parse(json).getAsJsonArray(); int size = jsonArr.size(); KeyPoint[] kpArray = new KeyPoint[size]; for(int i=0; i<size; i++){ KeyPoint kp = new KeyPoint(); JsonObject obj = (JsonObject) jsonArr.get(i); kp.pt = new Point( obj.get("x").getAsDouble(), obj.get("y").getAsDouble() ); kp.class_id = obj.get("class_id").getAsInt(); kp.size = obj.get("size").getAsFloat(); kp.angle = obj.get("angle").getAsFloat(); kp.octave = obj.get("octave").getAsInt(); kp.response = obj.get("response").getAsFloat(); kpArray[i] = kp; } result.fromArray(kpArray); return result; }
@Override public String doLogin(final String username, final String password) { try { String response = Util.postWebResponse("https://www.creeperhost.net/json/account/login", new HashMap<String, String>() {{ put("email", username); put("password", password); }}); if (response.equals("error")) { // Something went wrong, so lets just pretend everything fine and don't change the validation status } else { JsonElement jElement = new JsonParser().parse(response); JsonObject jObject = jElement.getAsJsonObject(); if (jObject.getAsJsonPrimitive("status").getAsString().equals("error")) { return jObject.getAsJsonPrimitive("message").getAsString(); } else { return "success:" + jObject.getAsJsonPrimitive("currency").getAsString() + ":" + jObject.getAsJsonPrimitive("userid").getAsString(); } } return "Unknown Error"; } catch (Throwable t) { CreeperHost.logger.error("Unable to do login", t); return "Unknown Error"; } }
@Test public void simple_shallow() { String template = "{ \"a\" : \"{{value}}\", \"b\": \"b\"}"; JsonObject document = (JsonObject) new JsonParser().parse(template); Map<String, String> paths = JsonUtil.getJsonPathsForTemplating(document); assertEquals(1, paths.size()); Object value = paths.get("$.a"); assertNotNull(value); assertEquals("{{value}}", value.toString()); }
public static String crunchifyPrettyJSONUtility(String simpleJSON) { JsonParser crunhifyParser = new JsonParser(); JsonObject json = crunhifyParser.parse(simpleJSON).getAsJsonObject(); Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); return prettyGson.toJson(json); }
private boolean isIssueOpen(int issueId) { String json = RestAssured.get("http://demo.bugify.com/api/issues.json", issueId).asString(); JsonElement parsed = new JsonParser().parse(json); JsonElement issues = parsed.getAsJsonObject().get("issues"); if (issues.getAsJsonArray().get(0).getAsJsonObject().get("state_name").toString().contains("Resolved")) { return false; } else { return true; } }
public ArrayList<String> getNames(String playername) throws IOException { String str = getPrevNames(playername); if (str == null) { Logger.WARNING.log("No name history was found"); } Iterator<JsonElement> iter = (new JsonParser()).parse(str).getAsJsonArray().iterator(); ArrayList<String> names = new ArrayList<String>(); while (iter.hasNext()) { names.add(iter.next().getAsJsonObject().get("name").getAsString().concat("\n")); } return names; }
protected int parseExposedPort(String dockerJson, int internalPort) { try { JsonArray jobj = new JsonParser().parse(dockerJson).getAsJsonArray(); JsonObject network = jobj.get(0).getAsJsonObject().get("NetworkSettings").getAsJsonObject(); JsonObject ports = network.getAsJsonObject("Ports"); JsonArray mappings = ports.getAsJsonArray("" + internalPort + "/tcp"); if (mappings != null) { return mappings.get(0).getAsJsonObject().get("HostPort").getAsInt(); } } catch (Exception ex) { logger.warn("Error parsing exposed port", ex); } return -1; }
public static String format(String uglyJson){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(uglyJson); String prettyJson = gson.toJson(jsonElement); return prettyJson; }
/** * Convert the configured browser specification from JSON to {@link Capabilities} object. * * @return {@link Capabilities} object for the configured browser specification */ public Capabilities getBrowserCaps() { if (browserCaps == null) { String jsonStr = null; String nameStr = getString(SeleniumSettings.BROWSER_NAME.key()); if (nameStr != null) { InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(nameStr + "Caps.json"); if (inputStream != null) { try { jsonStr = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException eaten) { LOGGER.warn("Unable to get browser configuration file contents: {}", eaten.getMessage()); } } if (jsonStr == null) { jsonStr = String.format(CAPS_PATTERN, nameStr); } } if (jsonStr == null) { jsonStr = getString(SeleniumSettings.BROWSER_CAPS.key()); } JsonObject json = new JsonParser().parse(JSON_HEAD + jsonStr + JSON_TAIL).getAsJsonObject(); GridNodeConfiguration config = GridNodeConfiguration.loadFromJSON(json); browserCaps = config.capabilities.get(0); } return browserCaps; }