org.json.simple.parser.JSONParser Java Examples
The following examples show how to use
org.json.simple.parser.JSONParser.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LambdaProxyHandlerTest.java From aws-lambda-proxy-java with MIT License | 6 votes |
@Test public void shouldReturnServerErrorAndReasonWhenMisconfigured() throws ParseException { ApiGatewayProxyRequest request = new ApiGatewayProxyRequestBuilder() .withHttpMethod(METHOD) .build(); LambdaProxyHandler<Configuration> handlerWithFailingConguration = new TestLambdaProxyHandlerWithFailingConguration(); handlerWithFailingConguration.registerMethodHandler(METHOD, c -> methodHandler); ApiGatewayProxyResponse actual = handlerWithFailingConguration.handleRequest(request, context); assertThat(actual).isNotNull(); assertThat(actual.getStatusCode()).isEqualTo(INTERNAL_SERVER_ERROR.getStatusCode()); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(actual.getBody()); assertThat(jsonObject.keySet()).contains("message", "cause"); assertThat((String) jsonObject.get("message")).contains("This service is mis-configured. Please contact your system administrator."); assertThat((String) jsonObject.get("cause")).contains("NullPointerException"); }
Example #2
Source File: AbstractHttpClient.java From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 | 6 votes |
/** * Builds URL params from input JSON string * * @param builder * @param jsonStr * @return * @throws ParseException */ public URIBuilder setParams(URIBuilder builder, String jsonStr) throws ParseException { if (jsonStr != null && !"".equals(jsonStr)) { try { JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(jsonStr); json.keySet().forEach((Key) -> { builder.setParameter(Key.toString(), (String) json.get(Key)); }); } catch (Exception ex) { DLogger.LogE(ex.getMessage()); LOG.log(Level.SEVERE, ex.getMessage(), ex); } } return builder; }
Example #3
Source File: CellStsUtils.java From cellery-security with Apache License 2.0 | 6 votes |
public static void buildCellStsConfiguration() throws CelleryCellSTSException { try { String configFilePath = CellStsUtils.getConfigFilePath(); String content = new String(Files.readAllBytes(Paths.get(configFilePath)), StandardCharsets.UTF_8); JSONObject config = (JSONObject) new JSONParser().parse(content); CellStsConfiguration.getInstance() .setCellName(getMyCellName()) .setStsEndpoint((String) config.get(Constants.Configs.CONFIG_STS_ENDPOINT)) .setUsername((String) config.get(Constants.Configs.CONFIG_AUTH_USERNAME)) .setPassword((String) config.get(Constants.Configs.CONFIG_AUTH_PASSWORD)) .setGlobalJWKEndpoint((String) config.get(Constants.Configs.CONFIG_GLOBAL_JWKS)) .setSignatureValidationEnabled(Boolean.parseBoolean(String.valueOf(config.get (Constants.Configs.CONFIG_SIGNATURE_VALIDATION_ENABLED)))) .setAudienceValidationEnabled(Boolean.parseBoolean(String.valueOf(config.get (Constants.Configs.CONFIG_AUDIENCE_VALIDATION_ENABLED)))) .setIssuerValidationEnabled(Boolean.parseBoolean(String.valueOf(config.get (Constants.Configs.CONFIG_ISSUER_VALIDATION_ENABLED)))) .setSTSOPAQueryPrefix((String) config.get(Constants.Configs.CONFIG_OPA_PREFIX)) .setAuthorizationEnabled(Boolean.parseBoolean(String.valueOf(config.get (Constants.Configs.CONFIG_AUTHORIZATION_ENABLED)))); } catch (ParseException | IOException e) { throw new CelleryCellSTSException("Error while setting up STS configurations", e); } }
Example #4
Source File: RSBuddyPriceGuide.java From Explvs-AIO with MIT License | 6 votes |
private static Optional<Integer> getPrice(final int itemID, final String type) { try { URL url = new URL("http://api.rsbuddy.com/grandExchange?a=guidePrice&i=" + itemID); URLConnection con = url.openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); try (InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { JSONParser jsonParser = new JSONParser(); JSONObject itemJSON = (JSONObject) jsonParser.parse(bufferedReader); int price = new Long((long) itemJSON.get(type)).intValue(); System.out.println("Got RSBuddy price"); return Optional.of(price); } } catch (Exception e) { System.out.println("Failed to get RSBuddy price"); } return Optional.empty(); }
Example #5
Source File: LoadoutPanel.java From Explvs-AIO with MIT License | 6 votes |
private Optional<URL> getIcon(final int itemID) { try { URL url = new URL("http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=" + itemID); URLConnection con = url.openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); try (InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { JSONParser jsonParser = new JSONParser(); JSONObject json = (JSONObject) jsonParser.parse(bufferedReader); JSONObject itemJSON = (JSONObject) json.get("item"); String iconURL = (String) itemJSON.get("icon"); return Optional.of(new URL(iconURL)); } } catch (Exception e) { e.printStackTrace(); System.out.println("Failed to get icon from RuneScape api"); } return Optional.empty(); }
Example #6
Source File: ParserASTJSON.java From soltix with Apache License 2.0 | 6 votes |
public AST parse(InputStream input) throws Exception { JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject)jsonParser.parse( new InputStreamReader(input, "UTF-8")); AST ast = new AST(); if (!Configuration.skipASTProcessing) { // Process JSON object to build AST JSONObjectToAST(ast, jsonObject, 0); } else { // For debugging: only print, don't interpret printJSONObject(jsonObject, 0); } return ast; }
Example #7
Source File: JsonRowMeta.java From hop with Apache License 2.0 | 6 votes |
public static IRowMeta fromJson(String rowMetaJson) throws ParseException, HopPluginException { JSONParser parser = new JSONParser(); JSONObject jRowMeta = (JSONObject) parser.parse( rowMetaJson ); IRowMeta rowMeta = new RowMeta( ); JSONArray jValues = (JSONArray) jRowMeta.get("values"); for (int v=0;v<jValues.size();v++) { JSONObject jValue = (JSONObject) jValues.get( v ); String name = (String) jValue.get("name"); long type = (long)jValue.get("type"); long length = (long)jValue.get("length"); long precision = (long)jValue.get("precision"); String conversionMask = (String) jValue.get("conversionMask"); IValueMeta valueMeta = ValueMetaFactory.createValueMeta( name, (int)type, (int)length, (int)precision ); valueMeta.setConversionMask( conversionMask ); rowMeta.addValueMeta( valueMeta ); } return rowMeta; }
Example #8
Source File: MultComponentService.java From singleton with Eclipse Public License 2.0 | 6 votes |
@SuppressWarnings({"unchecked" }) private TranslationDTO getTranslation(TranslationDTO translationDTO) throws ParseException, DataException { List<String> locales = translationDTO.getLocales(); List<String> components = translationDTO.getComponents(); List<String> bundles = multipleComponentsDao.get2JsonStrs( translationDTO.getProductName(), translationDTO.getVersion(), components, locales); JSONArray ja = new JSONArray(); for (int i = 0; i < bundles.size(); i++) { String s = (String) bundles.get(i); if (s.equalsIgnoreCase("")) { continue; } JSONObject jo = (JSONObject) new JSONParser().parse(s); ja.add(jo); } translationDTO.setBundles(ja); return translationDTO; }
Example #9
Source File: MojangUtil.java From VoxelGamesLibv2 with MIT License | 6 votes |
/** * Tries to fetch the current display name for the user * * @param id the id of the user to check * @return the current display name of that user * @throws IOException if something goes wrong * @throws VoxelGameLibException if the user has no display name */ @Nonnull public static String getDisplayName(@Nonnull UUID id) throws IOException, VoxelGameLibException { URL url = new URL(NAME_HISTORY_URL.replace("%1", id.toString().replace("-", ""))); System.out.println(url.toString()); Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(url.openStream()))); if (scanner.hasNext()) { String json = scanner.nextLine(); try { JSONArray jsonArray = (JSONArray) new JSONParser().parse(json); if (json.length() > 0) { return (String) ((JSONObject) jsonArray.get(0)).get("name"); } } catch (ParseException ignore) { } } throw new VoxelGameLibException("User has no name! " + id); }
Example #10
Source File: SingleComponentDTO.java From singleton with Eclipse Public License 2.0 | 6 votes |
/** * Get the ordered SingleComponentDTO from one JSON string * * @param jsonStr One JSON string can convert to a SingleComponentDTO object * @return SingleComponentDTO */ @SuppressWarnings("unchecked") public static SingleComponentDTO getSingleComponentDTOWithLinkedMessages(String jsonStr) throws ParseException { JSONParser parser = new JSONParser(); ContainerFactory containerFactory = getContainerFactory(); Map<String, Object> messages = new LinkedHashMap<String, Object>(); Map<String, Object> bundle = null; bundle = (Map<String, Object>) parser.parse(jsonStr, containerFactory); if (bundle == null) { return null; } SingleComponentDTO baseComponentMessagesDTO = new SingleComponentDTO(); baseComponentMessagesDTO.setId(Long.parseLong(bundle.get(ConstantsKeys.ID) == null ? "0" : bundle.get(ConstantsKeys.ID).toString())); baseComponentMessagesDTO.setComponent((String) bundle.get(ConstantsKeys.COMPONENT)); baseComponentMessagesDTO.setLocale((String) bundle.get(ConstantsKeys.lOCALE)); messages = (Map<String, Object>) bundle.get(ConstantsKeys.MESSAGES); baseComponentMessagesDTO.setMessages(messages); return baseComponentMessagesDTO; }
Example #11
Source File: JsonRowMeta.java From kettle-beam with Apache License 2.0 | 6 votes |
public static RowMetaInterface fromJson(String rowMetaJson) throws ParseException, KettlePluginException { JSONParser parser = new JSONParser(); JSONObject jRowMeta = (JSONObject) parser.parse( rowMetaJson ); RowMetaInterface rowMeta = new RowMeta( ); JSONArray jValues = (JSONArray) jRowMeta.get("values"); for (int v=0;v<jValues.size();v++) { JSONObject jValue = (JSONObject) jValues.get( v ); String name = (String) jValue.get("name"); long type = (long)jValue.get("type"); long length = (long)jValue.get("length"); long precision = (long)jValue.get("precision"); String conversionMask = (String) jValue.get("conversionMask"); ValueMetaInterface valueMeta = ValueMetaFactory.createValueMeta( name, (int)type, (int)length, (int)precision ); valueMeta.setConversionMask( conversionMask ); rowMeta.addValueMeta( valueMeta ); } return rowMeta; }
Example #12
Source File: LoadoutPanel.java From Explvs-AIO with MIT License | 6 votes |
private Optional<URL> getIcon(final int itemID) { try { URL url = new URL("http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=" + itemID); URLConnection con = url.openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); try (InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { JSONParser jsonParser = new JSONParser(); JSONObject json = (JSONObject) jsonParser.parse(bufferedReader); JSONObject itemJSON = (JSONObject) json.get("item"); String iconURL = (String) itemJSON.get("icon"); return Optional.of(new URL(iconURL)); } } catch (Exception e) { e.printStackTrace(); System.out.println("Failed to get icon from RuneScape api"); } return Optional.empty(); }
Example #13
Source File: Vocab.java From JFoolNLTK with Apache License 2.0 | 6 votes |
private void parseJson(String content) throws ParseException { JSONParser parser = new JSONParser(); Object obj = parser.parse(content); JSONObject jsonObject = (JSONObject) obj; Map<String, Integer> wordMap = parseStrMap((JSONObject) jsonObject.get("word_map")); Map<String, Integer> charMap = parseStrMap((JSONObject) jsonObject.get("char_map")); Map<Integer, String> segMap = parseIdMap((JSONObject) jsonObject.get("seg_map")); Map<Integer, String> posMap = parseIdMap((JSONObject) jsonObject.get("pos_map")); Map<Integer, String> nerMap = parseIdMap((JSONObject) jsonObject.get("ner_map")); charToId.setLabelToid(charMap); wordToId.setLabelToid(wordMap); idToSeg.setIdTolabel(segMap); idToPos.setIdTolabel(posMap); idToNer.setIdTolabel(nerMap); }
Example #14
Source File: ChannelURLService.java From proxylive with MIT License | 6 votes |
private JSONObject getJSONResponse(URL url) throws IOException, ParseException { JSONParser jsonParser = new JSONParser(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000); if (url.getUserInfo() != null) { String basicAuth = "Basic " + new String(Base64.getEncoder().encode(url.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", basicAuth); } connection.setRequestMethod("GET"); connection.connect(); if (connection.getResponseCode() != 200) { throw new IOException("Error on open stream:" + url); } JSONObject returnObject = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream(), "UTF-8")); connection.disconnect(); return returnObject; }
Example #15
Source File: LibraryProvider.java From netbeans with Apache License 2.0 | 6 votes |
/** * Update a library returned by {@link #findLibraries(java.lang.String)}. * The full library data is fetched and the {@code versions} property is * filled. * * @param library to be updated */ public void updateLibraryVersions(Library library) { Objects.nonNull(library); if(library.getVersions() != null && library.getVersions().length > 0) { return; } Library cachedLibrary = getCachedLibrary(library.getName()); if(cachedLibrary != null) { library.setVersions(cachedLibrary.getVersions()); return; } String data = readUrl(getLibraryDataUrl(library.getName())); if(data != null) { try { JSONParser parser = new JSONParser(); JSONObject libraryData = (JSONObject)parser.parse(data); updateLibrary(library, libraryData); entryCache.put(library.getName(), new WeakReference<>(library)); } catch (ParseException ex) { Logger.getLogger(LibraryProvider.class.getName()).log(Level.INFO, null, ex); } } }
Example #16
Source File: LibraryProvider.java From netbeans with Apache License 2.0 | 6 votes |
/** * Load the full data for the supplied library. All fields are populated, * including the {@code versions} property. * * @param libraryName * @return */ public Library loadLibrary(String libraryName) { Library cachedLibrary = getCachedLibrary(libraryName); if(cachedLibrary != null) { return cachedLibrary; } String data = readUrl(getLibraryDataUrl(libraryName)); if (data != null) { try { JSONParser parser = new JSONParser(); JSONObject libraryData = (JSONObject) parser.parse(data); Library library = createLibrary(libraryData); entryCache.put(library.getName(), new WeakReference<>(library)); return library; } catch (ParseException ex) { Logger.getLogger(LibraryProvider.class.getName()).log(Level.INFO, null, ex); } } return null; }
Example #17
Source File: LibraryProvider.java From netbeans with Apache License 2.0 | 6 votes |
/** * Parses the given JSON result of the search. * * @param data search result. * * @return libraries returned in the search result. */ Library[] parse(String data) { Library[] libraries = null; try { JSONParser parser = new JSONParser(); JSONObject searchResult = (JSONObject) parser.parse(data); JSONArray libraryArray = (JSONArray) searchResult.get(PROPERTY_RESULT); libraries = new Library[libraryArray.size()]; for (int i = 0; i < libraries.length; i++) { JSONObject libraryData = (JSONObject) libraryArray.get(i); libraries[i] = createLibrary(libraryData); } } catch (ParseException pex) { Logger.getLogger(LibraryProvider.class.getName()).log(Level.INFO, null, pex); } return libraries; }
Example #18
Source File: ServerConnection.java From netbeans with Apache License 2.0 | 6 votes |
private void received(Listener listener, String tools, String message) throws ParseException, IOException { //System.out.println("RECEIVED: tools: '"+tools+"', message: '"+message+"'"); fireReceived(message); LOG.log(Level.FINE, "RECEIVED: {0}, {1}", new Object[]{tools, message}); if (message.isEmpty()) { return ; } JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(message, containerFactory); V8Request request = JSONReader.getRequest(obj); ResponseProvider rp = listener.request(request); if (V8Command.Disconnect.equals(request.getCommand())) { try { closeCurrentConnection(); } catch (IOException ioex) {} } if (rp != null) { rp.sendTo(this); } }
Example #19
Source File: RemoteConnectorServiceImpl.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
public static JSONObject doExecuteJSONRequest(RemoteConnectorRequest request, RemoteConnectorService service) throws ParseException, IOException, AuthenticationException { // Set as JSON request.setContentType(MimetypeMap.MIMETYPE_JSON); // Perform the request RemoteConnectorResponse response = service.executeRequest(request); // Parse this as JSON JSONParser parser = new JSONParser(); String jsonText = response.getResponseBodyAsString(); Object json = parser.parse(jsonText); // Check it's the right type and return if (json instanceof JSONObject) { return (JSONObject)json; } else { throw new ParseException(0, json); } }
Example #20
Source File: RSBuddyPriceGuide.java From Explvs-AIO with MIT License | 6 votes |
private static Optional<Integer> getPrice(final int itemID, final String type) { try { URL url = new URL("http://api.rsbuddy.com/grandExchange?a=guidePrice&i=" + itemID); URLConnection con = url.openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); try (InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { JSONParser jsonParser = new JSONParser(); JSONObject itemJSON = (JSONObject) jsonParser.parse(bufferedReader); int price = new Long((long) itemJSON.get(type)).intValue(); System.out.println("Got RSBuddy price"); return Optional.of(price); } } catch (Exception e) { System.out.println("Failed to get RSBuddy price"); } return Optional.empty(); }
Example #21
Source File: UIComponents.java From BedrockConnect with GNU General Public License v3.0 | 6 votes |
public static ArrayList<String> getFormData(String data) { JSONParser parser = new JSONParser(); // If no server data if(data == null) return new ArrayList<>(); try { JSONArray obj = (JSONArray) parser.parse(data); ArrayList<String> strings = new ArrayList<>(); for(int i=0;i<obj.size();i++) { strings.add(obj.get(i).toString()); } return strings; } catch(ParseException e) { System.out.println(e.toString()); } return null; }
Example #22
Source File: VersionChecker.java From Explvs-AIO with MIT License | 5 votes |
private static Optional<JSONObject> getLatestGitHubReleaseJSON() { try { URL url = new URL(GITHUB_API_LATEST_RELEASE_URL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); try (InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { return Optional.of((JSONObject) (new JSONParser().parse(bufferedReader))); } } catch (IOException | ParseException e) { e.printStackTrace(); } return Optional.empty(); }
Example #23
Source File: TestHttpFSServer.java From hadoop with Apache License 2.0 | 5 votes |
/** * Parse xAttrs from JSON result of GETXATTRS call, return xAttrs Map. * @param statusJson JSON from GETXATTRS * @return Map<String, byte[]> xAttrs Map * @throws Exception */ private Map<String, byte[]> getXAttrs(String statusJson) throws Exception { Map<String, byte[]> xAttrs = Maps.newHashMap(); JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(statusJson); JSONArray jsonXAttrs = (JSONArray) jsonObject.get("XAttrs"); if (jsonXAttrs != null) { for (Object a : jsonXAttrs) { String name = (String) ((JSONObject)a).get("name"); String value = (String) ((JSONObject)a).get("value"); xAttrs.put(name, decodeXAttrValue(value)); } } return xAttrs; }
Example #24
Source File: ProfilingLogRecording.java From soltix with Apache License 2.0 | 5 votes |
public void loadEventLog(String path) throws Exception { BufferedReader br = new BufferedReader(new FileReader(path)); String line; recordedResultList = new ArrayList<ProfilingEvent>(); while ((line = br.readLine()) != null) { JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject)jsonParser.parse(line); ProfilingEvent event = ProfilingEvent.fromJSON(ast, jsonObject); if (event == null) { continue; } recordedResultList.add(event); if (!event.getIsOrdinaryUserEvent()) { /* // A log for multiple contracts must be allowed at least for inter-contract // calls if (contract != null) { if (contract != event.getContract()) { throw new Exception("Event log contains events from more than one contract"); } } else*/ { contract = event.getContract(); // Infer the containing function of this first event as well firstEventFunction = ast.getFunctionByStatementId(event.getStatementID()); } } } currentReplayIndex = 0; // Finalize environment variables for (ProfilingEvent eventData : recordedResultList) { if (eventData.getStatement() != null) { eventData.getStatement().getVariableEnvironment().finishAddingValues(); } } }
Example #25
Source File: TestHttpFSServer.java From hadoop with Apache License 2.0 | 5 votes |
/** * Given the JSON output from the GETACLSTATUS call, return the * 'entries' value as a List<String>. * @param statusJson JSON from GETACLSTATUS * @return A List of Strings which are the elements of the ACL entries * @throws Exception */ private List<String> getAclEntries ( String statusJson ) throws Exception { List<String> entries = new ArrayList<String>(); JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(statusJson); JSONObject details = (JSONObject) jsonObject.get("AclStatus"); JSONArray jsonEntries = (JSONArray) details.get("entries"); if ( jsonEntries != null ) { for (Object e : jsonEntries) { entries.add(e.toString()); } } return entries; }
Example #26
Source File: NodeMessage.java From java-trader with Apache License 2.0 | 5 votes |
public static NodeMessage fromString(String jsonStr) throws Exception { JSONObject json = (JSONObject)(new JSONParser()).parse(jsonStr); MsgType type = MsgType.valueOf((String) json.remove(FIELD_TYPE)); int id = ConversionUtil.toInt(json.remove(FIELD_ID)); int reqId = ConversionUtil.toInt(json.remove(FIELD_REQID)); int corrId = ConversionUtil.toInt(json.remove(FIELD_CORRID)); int errorCode = ConversionUtil.toInt(json.remove(FIELD_ERROR_CODE)); String errorMsg = (String)json.remove(FIELD_ERROR_MSG); Map<String, Object> fields = json; NodeMessage result = new NodeMessage(type, id, reqId, corrId, fields); result.setErrCode(errorCode); result.setErrMsg(errorMsg); return result; }
Example #27
Source File: LambdaProxyHandlerTest.java From aws-lambda-proxy-java with MIT License | 5 votes |
@Test public void shouldPassThroughErrorMessageFromMethodHandlerInvocationIfDebug() throws Exception { Map<String, String> headers = new ConcurrentHashMap<>(); headers.put(CONTENT_TYPE, CONTENT_TYPE_1.toString()); headers.put(ACCEPT, ACCEPT_TYPE_1.toString()); randomiseKeyValues(headers); ApiGatewayProxyRequest request = new ApiGatewayProxyRequestBuilder() .withHttpMethod(METHOD) .withHeaders(headers) .withContext(context) .build(); String message = "Some message"; RuntimeException cause = new RuntimeException(); StackTraceElement[] expectedStackTrace = new StackTraceElement[2]; String declaringClass1 = "declaringClass1"; String methodName1 = "methodName1"; String fileName1 = "fileName1"; int lineNumber1 = 1; expectedStackTrace[0] = new StackTraceElement(declaringClass1, methodName1, fileName1, lineNumber1); String declaringClass2 = "declaringClass2"; String methodName2 = "methodName2"; String fileName2 = "fileName2"; int lineNumber2 = 2; expectedStackTrace[1] = new StackTraceElement(declaringClass2, methodName2, fileName2, lineNumber2); cause.setStackTrace(expectedStackTrace); when(methodHandler.handle(request, singletonList(CONTENT_TYPE_1), singletonList(ACCEPT_TYPE_1), context)) .thenThrow(new RuntimeException(message, cause)); handler.registerMethodHandler(METHOD, c -> methodHandler); ApiGatewayProxyResponse response = handler.handleRequest(request, context); assertThat(response).isNotNull(); assertThat(response.getStatusCode()).isEqualTo(INTERNAL_SERVER_ERROR.getStatusCode()); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(response.getBody()); assertThat(jsonObject.keySet()).contains("message", "cause"); assertThat(jsonObject.get("message")).isEqualTo(message); assertThat((String) jsonObject.get("cause")).contains(String.format("%s.%s(%s:%s)", declaringClass1, methodName1, fileName1, lineNumber1)); assertThat((String) jsonObject.get("cause")).contains(String.format("%s.%s(%s:%s)", declaringClass2, methodName2, fileName2, lineNumber2)); }
Example #28
Source File: ChannelTVHeadendService.java From proxylive with MIT License | 5 votes |
private JSONObject getTvheadendResponse(String request) throws MalformedURLException, ProtocolException, IOException, ParseException { JSONParser jsonParser = new JSONParser(); HttpURLConnection connection = getURLConnection(request); if (connection.getResponseCode() != 200) { throw new IOException("Error on open stream:" + request); } JSONObject returnObject = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream(), "UTF-8")); connection.disconnect(); return returnObject; }
Example #29
Source File: PlexAuthenticationService.java From proxylive with MIT License | 5 votes |
private JSONObject getUserData(String user, String pass) throws MalformedURLException, IOException, ParseException { URL url = new URL(String.format("https://%s:%[email protected]/users/sign_in.json", URLEncoder.encode(user,"UTF-8"), URLEncoder.encode(pass,"UTF-8"))); HttpURLConnection connection = createConnection(url); connection.setRequestProperty("X-Plex-Client-Identifier", "proxylive"); connection.setRequestMethod("POST"); connection.connect(); if (connection.getResponseCode() != 201) { return null; } JSONParser jsonParser = new JSONParser(); JSONObject response = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream(), "UTF-8")); return (JSONObject) response.get("user"); }
Example #30
Source File: OSRSPriceGuide.java From Explvs-AIO with MIT License | 5 votes |
public static Optional<Integer> getPrice(final int itemID) { try { URL url = new URL("http://services.runescape.com/m=itemdb_oldschool/api/catalogue/detail.json?item=" + itemID); URLConnection con = url.openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); try (InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream()); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { JSONParser jsonParser = new JSONParser(); JSONObject json = (JSONObject) jsonParser.parse(bufferedReader); JSONObject itemJSON = (JSONObject) json.get("item"); JSONObject currentPriceData = (JSONObject) itemJSON.get("current"); Object currentPriceObj = currentPriceData.get("price"); int currentPrice; if (currentPriceObj instanceof String) { currentPrice = parsePriceStr((String) currentPriceData.get("price")); } else if (currentPriceObj instanceof Long) { currentPrice = ((Long) currentPriceObj).intValue(); } else { currentPrice = (int) currentPriceObj; } return Optional.of(currentPrice); } } catch (Exception e) { e.printStackTrace(); System.out.println("Failed to get price from RuneScape api"); } return Optional.empty(); }