List of usage examples for org.json.simple JSONValue parse
public static Object parse(String s)
From source file:importer.handler.post.ImporterPostHandler.java
/** * Add metadata automatically/*from w w w .j a v a 2 s .c om*/ * @param version1 the default version of the MVD */ protected void addMetadata(String version1) throws ImporterException { try { JSONObject docMetadata = new JSONObject(); JSONObject projectMetadata = null; docMetadata.put(JSONKeys.DOCID, docid); docMetadata.put(JSONKeys.ENCODING, encoding); String section = getSection(); if (section.length() > 0) docMetadata.put(JSONKeys.SECTION, section); String subSection = getSubsection(); if (subSection.length() > 0) docMetadata.put(JSONKeys.SUBSECTION, subSection); docMetadata.put(JSONKeys.VERSION1, version1); // add title String project = Connector.getConnection().getFromDb(Database.PROJECTS, trimDocid(docid, 3)); if (project == null) project = Connector.getConnection().getFromDb(Database.PROJECTS, trimDocid(docid, 2)); if (project != null) { projectMetadata = (JSONObject) JSONValue.parse(project); docMetadata.put(JSONKeys.AUTHOR, projectMetadata.get(JSONKeys.AUTHOR)); } else docMetadata.put(JSONKeys.AUTHOR, getAuthor()); if (projectMetadata != null && projectMetadata.get(JSONKeys.WORK) != null && title.equals("untitled")) docMetadata.put(JSONKeys.TITLE, projectMetadata.get(JSONKeys.WORK)); else docMetadata.put(JSONKeys.TITLE, title); Connector.getConnection().putToDb(Database.METADATA, docid, docMetadata.toJSONString()); } catch (Exception e) { throw new ImporterException(e); } }
From source file:backtype.storm.multilang.JsonSerializer.java
private Object readMessage() throws IOException, NoOutputException { String string = readString(); Object msg = JSONValue.parse(string); if (msg != null) { return msg; } else {/* ww w . j a va 2 s . co m*/ throw new IOException("unable to parse: " + string); } }
From source file:com.memetix.mst.MicrosoftTranslatorAPI.java
/** * Forms an HTTP request, sends it using GET method and returns the result of the request as a String. * /*from w w w . java 2s .c o m*/ * @param url The URL to query for a String response. * @return The translated String. * @throws Exception on error. */ private static String retrieveResponse(final URL url) throws Exception { if (clientId != null && clientSecret != null && System.currentTimeMillis() > tokenExpiration) { String tokenJson = getToken(clientId, clientSecret); Integer expiresIn = Integer .parseInt((String) ((JSONObject) JSONValue.parse(tokenJson)).get("expires_in")); tokenExpiration = System.currentTimeMillis() + ((expiresIn * 1000) - 1); token = "Bearer " + (String) ((JSONObject) JSONValue.parse(tokenJson)).get("access_token"); } final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); if (referrer != null) uc.setRequestProperty("referer", referrer); uc.setRequestProperty("Content-Type", contentType + "; charset=" + ENCODING); uc.setRequestProperty("Accept-Charset", ENCODING); if (token != null) { uc.setRequestProperty("Authorization", token); } uc.setRequestMethod("GET"); uc.setDoOutput(true); try { final int responseCode = uc.getResponseCode(); final String result = inputStreamToString(uc.getInputStream()); if (responseCode != 200) { throw new Exception("Error from Microsoft Translator API: " + result); } return result; } finally { if (uc != null) { uc.disconnect(); } } }
From source file:com.gmail.bleedobsidian.areaprotect.Updater.java
/** * Query ServerMods API for project variables. * /*from w w w .jav a 2s . co m*/ * @return If successful or not. */ private boolean query() { try { final URLConnection con = this.url.openConnection(); con.setConnectTimeout(5000); if (this.apiKey != null) { con.addRequestProperty("X-API-Key", this.apiKey); } con.addRequestProperty("User-Agent", this.plugin.getName() + " Updater"); con.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.result = UpdateResult.ERROR_ID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get("name"); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl"); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get("releaseType"); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get("gameVersion"); return true; } catch (IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.result = UpdateResult.ERROR_APIKEY; } else { this.result = UpdateResult.ERROR_SERVER; } return false; } }
From source file:com.jgoetsch.eventtrader.source.ApeStreamingMsgSource.java
private JSONArray executeRequest(HttpClient client, HttpUriRequest request) { try {/* ww w. j a v a2 s . co m*/ HttpResponse rsp = client.execute(request); HttpEntity entity = rsp.getEntity(); if (rsp.getStatusLine().getStatusCode() >= 400 || entity == null) { log.error("HTTP request to " + request.getURI() + " failed with status " + rsp.getStatusLine()); return null; } else { return (JSONArray) JSONValue.parse(new BufferedReader(new InputStreamReader(entity.getContent()))); } } catch (Exception e) { log.warn("Exception reading or parsing message source", e); return null; } finally { request.abort(); } }
From source file:com.turt2live.uuid.turt2live.v1.ApiV1Service.java
@Override public List<PlayerRecord> doBulkLookup(String... playerNames) { String list = combine(playerNames); String response = doUrlRequest(getConnectionUrl() + "/uuid/list/" + list); if (response != null) { JSONObject json = (JSONObject) JSONValue.parse(response); if (json.containsKey("results")) { JSONObject object = (JSONObject) json.get("results"); List<PlayerRecord> records = new ArrayList<>(); for (Object key : object.keySet()) { String name = key.toString(); UUID uuid = convertUuid((String) object.get(key)); if (uuid == null || name.equals("unknown")) continue; PlayerRecord record = new Turt2LivePlayerRecord(uuid, name); records.add(record);// w ww. j a v a 2 s .c o m } return records; } } return null; }
From source file:com.twosigma.beaker.core.module.config.DefaultBeakerConfig.java
@Inject public DefaultBeakerConfig(BeakerConfigPref pref, GeneralUtils utils) throws UnknownHostException, IOException, InterruptedException { this.installDir = System.getProperty("user.dir"); this.searchDirs = new String[1]; this.searchDirs[0] = this.installDir; this.useKerberos = pref.getUseKerberos(); this.portBase = pref.getPortBase(); this.reservedPortCount = 4; this.dotDir = System.getProperty("user.home") + "/.beaker/v1"; this.pluginDir = this.installDir + "/config/plugins/eval"; utils.ensureDirectoryExists(this.dotDir); this.nginxDir = this.installDir + "/nginx"; if (System.getProperty("beaker.nginx.bin.dir") != null) { this.nginxBinDir = System.getProperty("beaker.nginx.bin.dir"); } else {//from ww w . j av a 2s.c om this.nginxBinDir = ""; // assuming nginx is available in PATH } this.nginxServDir = utils.createTempDirectory(this.dotDir, "nginx"); this.nginxStaticDir = this.installDir + "/src/main/web"; this.nginxExtraRules = ""; this.nginxPluginRules = new HashMap<>(); String configDir = this.dotDir + "/config"; utils.ensureDirectoryExists(configDir); final String defaultConfigFile = this.installDir + "/config/beaker.conf.json"; this.configFileUrl = defaultConfigFile; final String defaultPreferenceFile = this.installDir + "/config/beaker.pref.json"; final String preferenceFile = configDir + "/beaker.pref.json"; utils.ensureFileHasContent(preferenceFile, defaultPreferenceFile); this.preferenceFileUrl = preferenceFile; String content = utils.readFile(this.preferenceFileUrl); JSONObject obj = (JSONObject) JSONValue.parse(content); if (obj.get("gist_server") != null) this.gist_server = (String) obj.get("gist_server"); else this.gist_server = "https://api.github.com/gists"; if (obj.get("sharing_server") != null) this.sharing_server = (String) obj.get("sharing_server"); else this.sharing_server = "http://sharing.beakernotebook.com/gist/anonymous"; this.prefs = obj; final String prefDefaultNotebookUrl = pref.getDefaultNotebookUrl(); final String mainDefaultNotebookPath = this.dotDir + "/config/default.bkr"; final String defaultDefaultNotebookPath = this.installDir + "/config/default.bkr"; if (prefDefaultNotebookUrl != null) { this.defaultNotebookUrl = prefDefaultNotebookUrl; } else { File f = new File(mainDefaultNotebookPath); if (f.exists()) this.defaultNotebookUrl = mainDefaultNotebookPath; else this.defaultNotebookUrl = defaultDefaultNotebookPath; } String varDir = this.dotDir + "/var"; utils.ensureDirectoryExists(varDir); this.recentNotebooksFileUrl = varDir + "/recentNotebooks"; this.sessionBackupDir = varDir + "/sessionBackups"; utils.ensureDirectoryExists(this.sessionBackupDir); this.pluginLocations = new HashMap<>(); this.pluginOptions = pref.getPluginOptions(); this.pluginEnvps = new HashMap<>(); augmentPluginOptions(); this.publicServer = pref.getPublicServer(); this.useHttpsCert = pref.getUseHttpsCert(); this.useHttpsKey = pref.getUseHttpsKey(); this.requirePassword = pref.getRequirePassword(); this.listenInterface = pref.getListenInterface(); this.authCookie = RandomStringUtils.random(40, true, true); // XXX user might provide their own hash in beaker.config.json String password = RandomStringUtils.random(15, true, true); this.passwordHash = hash(password); this.password = password; if (this.publicServer && (this.useHttpsCert == null || this.useHttpsKey == null)) { String cert = this.nginxServDir + "/ssl_cert.pem"; String tmp = this.nginxServDir + "/cert.tmp"; PrintWriter pw = new PrintWriter(tmp); for (int i = 0; i < 10; i++) pw.printf("\n"); pw.close(); // XXX I am baffled as to why using sh and this pipe is // necessary, but if you just exec openssl and write into its // stdin then it hangs. String[] cmd = { "sh", "-c", "cat " + tmp + " | openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout " + cert + " -out " + cert }; Process proc = Runtime.getRuntime().exec(cmd); proc.waitFor(); } this.version = utils.readFile(this.installDir + "/config/version"); this.buildTime = utils.readFile(this.installDir + "/config/build_time"); this.hash = utils.readFile(this.installDir + "/config/hash"); }
From source file:anotadorderelacoes.model.Sentenca.java
/** * Cria um objeto Sentenca a partir de uma sentena codificada no formato * JSON./*from ww w. j a v a2s . co m*/ * <p> * Lana uma exceo NullPointerException quando recebe um arquivo com * formatao invlida. * * @param sentencaJson String que codifica um objeto Sentenca em formato * JSON */ public Sentenca(String sentencaJson) throws NullPointerException { JSONObject json = (JSONObject) JSONValue.parse(sentencaJson); id = ((Long) json.get("id")).intValue(); texto = (String) json.get("texto"); //System.out.println( "DEBUG: Parsing sentence " + id ); //System.out.println( sentencaJson ); // Os tokens so delimitados de acordo com suas posies na sentena posicoesInicioTokens = new ArrayList<Integer>(); posicoesFimTokens = new ArrayList<Integer>(); int caracteresAcumulados = 0; tokens = new ArrayList<Token>(); for (Object tokenJson : (JSONArray) json.get("tokens")) { if (caracteresAcumulados > 0) ++caracteresAcumulados; Token t = new Token(tokenJson.toString()); tokens.add(t); posicoesInicioTokens.add(caracteresAcumulados); caracteresAcumulados += t.getToken().length(); posicoesFimTokens.add(caracteresAcumulados); } termos = new ArrayList<Termo>(); if (json.get("termos") != null) for (Object termoJson : (JSONArray) json.get("termos")) { Integer de = ((Long) ((JSONObject) termoJson).get("de")).intValue(); Integer ate = ((Long) ((JSONObject) termoJson).get("ate")).intValue(); String t = tokens.get(de).getToken(); for (int i = de + 1; i <= ate; ++i) t += " " + tokens.get(i).getToken(); termos.add(new Termo(de, ate, t)); } relacoes = new ArrayList<Relacao>(); if (json.get("relacoes") != null) { for (Object relacaoJson : (JSONArray) json.get("relacoes")) { String relacao = (String) ((JSONObject) relacaoJson).get("r"); Integer termo1 = ((Long) ((JSONObject) relacaoJson).get("t1")).intValue(); Integer termo2 = ((Long) ((JSONObject) relacaoJson).get("t2")).intValue(); relacoes.add(new Relacao(relacao, new Termo(termos.get(termo1)), new Termo(termos.get(termo2)))); } } comentarios = ""; if (json.get("comentarios") != null) comentarios = (String) json.get("comentarios"); anotadores = new ArrayList<String>(); if (json.get("anotadores") != null) for (Object anotador : (JSONArray) json.get("anotadores")) anotadores.add((String) anotador); anotada = false; if (json.get("anotada") != null) anotada = (Boolean) json.get("anotada"); ignorada = false; if (json.get("ignorada") != null) ignorada = (Boolean) json.get("ignorada"); }
From source file:com.turt2live.uuid.turt2live.v2.ApiV2Service.java
@Override public List<PlayerRecord> doBulkLookup(UUID... uuids) { String list = combine(uuids); String response = doUrlRequest(getConnectionUrl() + "/name/list/" + list); if (response != null) { JSONObject json = (JSONObject) JSONValue.parse(response); if (json.containsKey("results")) { JSONObject object = (JSONObject) json.get("results"); List<PlayerRecord> records = new ArrayList<>(); for (Object key : object.keySet()) { UUID uuid = UUID.fromString(key.toString()); String name = (String) object.get(key); if (uuid == null || name.equals("unknown")) continue; // Note: v2 returns a v1 compatible player record PlayerRecord record = new Turt2LivePlayerRecord(uuid, name); records.add(record);/*from w w w .j a v a 2 s .co m*/ } return records; } } return null; }
From source file:com.sforce.cd.apexUnit.client.codeCoverage.WebServiceInvoker.java
public static JSONObject doGet(String relativeServiceURL, String accessToken) { LOG.debug("relativeServiceURL in doGet method:" + relativeServiceURL); HttpClient httpclient = new HttpClient(); GetMethod get = null;//w ww. j a v a 2 s.c o m String authorizationServerURL = CommandLineArguments.getOrgUrl() + relativeServiceURL; get = new GetMethod(authorizationServerURL); get.addRequestHeader("Content-Type", "application/json"); get.setRequestHeader("Authorization", "Bearer " + accessToken); LOG.debug("Start GET operation for the url..." + authorizationServerURL); InputStream instream = null; try { instream = executeHTTPMethod(httpclient, get, authorizationServerURL); LOG.debug("done with get operation"); JSONObject json = (JSONObject) JSONValue.parse(new InputStreamReader(instream)); LOG.debug("is json null? :" + json == null ? "true" : "false"); if (json != null) { if (LOG.isDebugEnabled()) { LOG.debug("ToolingApi.get response: " + json.toString()); Set<String> keys = castSet(String.class, json.keySet()); Iterator<String> jsonKeyIter = keys.iterator(); LOG.debug("Response for the GET method: "); while (jsonKeyIter.hasNext()) { String key = jsonKeyIter.next(); LOG.debug("key : " + key + ". Value : " + json.get(key) + "\n"); // TODO if query results are too large, only 1st batch // of results // are returned. Need to use the identifier in an // additional query // to retrieve rest of the next batch of results if (key.equals("nextRecordsUrl")) { // fire query to the value for this key // doGet((String) json.get(key), accessToken); try { authorizationServerURL = CommandLineArguments.getOrgUrl() + (String) json.get(key); get.setURI(new URI(authorizationServerURL, false)); instream = executeHTTPMethod(httpclient, get, authorizationServerURL); JSONObject newJson = (JSONObject) JSONValue.parse(new InputStreamReader(instream)); if (newJson != null) { Set<String> newKeys = castSet(String.class, json.keySet()); Iterator<String> newJsonKeyIter = newKeys.iterator(); while (newJsonKeyIter.hasNext()) { String newKey = newJsonKeyIter.next(); json.put(newKey, newJson.get(newKey)); LOG.debug("newkey : " + newKey + ". NewValue : " + newJson.get(newKey) + "\n"); } } } catch (URIException e) { ApexUnitUtils.shutDownWithDebugLog(e, "URI exception while fetching subsequent batch of result"); } } } } } return json; } finally { get.releaseConnection(); try { if (instream != null) { instream.close(); } } catch (IOException e) { ApexUnitUtils.shutDownWithDebugLog(e, "Encountered IO exception when closing the stream after reading response from the get method. The error says: " + e.getMessage()); } } }