Java 类org.json.simple.JSONValue 实例源码

项目:fuck_zookeeper    文件:FileLoader.java   
String handleRequest(JsonRequest request) throws Exception
   {
String output = "";

String file = request.getString("path", "/");
JSONObject o = new JSONObject();
try {
    this.source.addSource(file);
    o.put("status", "OK");

} catch (Exception e) {
    o.put("status", "ERR");
    o.put("error",  e.toString());
}

return JSONValue.toJSONString(o);
   }
项目:https-github.com-apache-zookeeper    文件:FileLoader.java   
String handleRequest(JsonRequest request) throws Exception
   {
String output = "";

String file = request.getString("path", "/");
JSONObject o = new JSONObject();
try {
    this.source.addSource(file);
    o.put("status", "OK");

} catch (Exception e) {
    o.put("status", "ERR");
    o.put("error",  e.toString());
}

return JSONValue.toJSONString(o);
   }
项目:ZooKeeper    文件:FileLoader.java   
String handleRequest(JsonRequest request) throws Exception
   {
String output = "";

String file = request.getString("path", "/");
JSONObject o = new JSONObject();
try {
    this.source.addSource(file);
    o.put("status", "OK");

} catch (Exception e) {
    o.put("status", "ERR");
    o.put("error",  e.toString());
}

return JSONValue.toJSONString(o);
   }
项目:SecureKeeper    文件:FileLoader.java   
String handleRequest(JsonRequest request) throws Exception
   {
String output = "";

String file = request.getString("path", "/");
JSONObject o = new JSONObject();
try {
    this.source.addSource(file);
    o.put("status", "OK");

} catch (Exception e) {
    o.put("status", "ERR");
    o.put("error",  e.toString());
}

return JSONValue.toJSONString(o);
   }
项目:incubator-netbeans    文件:ScriptExecutorImpl.java   
@Override
public Object execute(String script) {
    StringBuilder sb = new StringBuilder();
    // Callback for scripts that want to send some message back to page-inspection.
    // We utilize custom alert handling of WebEngine for this purpose.
    sb.append("postMessageToNetBeans=function(e) {alert('"); // NOI18N
    sb.append(WebBrowserImpl.PAGE_INSPECTION_PREFIX);
    sb.append("'+JSON.stringify(e));};\n"); // NOI18N
    String quoted = '\"'+JSONValue.escape(script)+'\"';
    // We don't want to depend on what is the type of WebBrowser.executeJavaScript()
    // for various types of script results => we stringify the result
    // (i.e. pass strings only through executeJavaScript()). We decode
    // the strigified result then.
    sb.append("JSON.stringify({result : eval(").append(quoted).append(")});"); // NOI18N
    String wrappedScript = sb.toString();
    Object result = browserTab.executeJavaScript(wrappedScript);
    String txtResult = result.toString();
    try {
        JSONObject jsonResult = (JSONObject)JSONValue.parseWithException(txtResult);
        return jsonResult.get("result"); // NOI18N
    } catch (ParseException ex) {
        Logger.getLogger(ScriptExecutorImpl.class.getName()).log(Level.INFO, null, ex);
        return ScriptExecutor.ERROR_RESULT;
    }
}
项目:ShowPolicyPackage    文件:HtmlUtils.java   
/**
 * This function writes the info of the rulbase to the html file
 * @param htmlFile The html to write to
 * @param details {@link FileDetails} contain info about the html file
 * @throws IOException
 */
public void setRulebaseHtmlFile(PrintStream htmlFile , FileDetails details) throws IOException{

    htmlFile.println("\t\tvar rulebase = " + details.getRulebaseData().getRulebaseDataContent() + ";");
    htmlFile.print("\t\tvar uid_to_name = ");
    htmlFile.print(JSONValue.toJSONString(details.getUidToName()));
    htmlFile.println(";");

    htmlFile.print("\t\tvar failed_creating_layer = ");
    htmlFile.print(JSONValue.toJSONString(details.getRulebaseData().isFailedCreatingRulebase()));
    htmlFile.println(";");

    htmlFile.print("\t\tvar inline_layer_uid_to_file_name = ");
    htmlFile.print(JSONValue.toJSONString(details.getRulebaseData().getInlineLayerUidToFileNameMap()));
    htmlFile.println(";");

    setDataInHtmlFile(htmlFile, details);
}
项目:EmojiChat    文件:EmojiChatUpdateChecker.java   
/**
 * Checks if updates are available.
 */
private void checkForUpdates() {
    try {
        URL url = new URL("https://api.spiget.org/v2/resources/50955/versions?size=1&sort=-id");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.addRequestProperty("User-Agent", "EmojiChat Update Checker"); // Sets the user-agent

        InputStream inputStream = connection.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream);

        JSONArray value = (JSONArray) JSONValue.parseWithException(reader);

        latestVersion = Double.parseDouble(((JSONObject) value.get(value.size() - 1)).get("name").toString());

        updateAvailable = currentVersion < latestVersion;
    } catch (Exception ignored) { // Something happened, not sure what (possibly no internet connection), so no updates available
        updateAvailable = false;
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:Performance.java   
@SuppressWarnings("rawtypes")
private void createHar(String pt, String rt) {
    Har<String, Log> har = new Har<>();
    Page p = new Page(pt, har.pages());
    har.addPage(p);
    for (Object res : (JSONArray) JSONValue.parse(rt)) {
        JSONObject jse = (JSONObject) res;
        if (jse.size() > 14) {
            Entry e = new Entry(jse.toJSONString(), p);
            har.addEntry(e);
        }
    }
    har.addRaw(pt, rt);
    Control.ReportManager.addHar(har, (TestCaseReport) Report,
            escapeName(Data));
}
项目:Cognizant-Intelligent-Test-Scripter    文件:Performance.java   
/**
    * parse and map the pages and its page timings
    *
    * @param data json data
    * @return json map
    */

private static JSONObject getPageMap(String data) {
       JSONObject pageMap = new JSONObject();
       JSONObject ob = (JSONObject) JSONValue.parse(data);
       for (Object tc : ob.keySet()) {
           JSONArray hars = (JSONArray) ((JSONObject) ob.get(tc)).get("har");
           for (Object e : hars) {
               JSONObject har = (JSONObject) ((JSONObject) e).get("har");
               JSONObject page = (JSONObject) ((JSONArray) (((JSONObject) har.get("log")).get("pages"))).get(0);
               Object pagename = ((JSONObject) har.get("config")).get("name");
               if (!pageMap.containsKey(pagename)) {
                   pageMap.put(pagename, new JSONArray());
               }
               JSONObject pageData = (JSONObject) page.get("pageTimings");
               pageData.put("config", har.get("config"));
               ((JSONArray) pageMap.get(pagename)).add(pageData);
           }
       }
       return pageMap;
   }
项目:alfresco-remote-api    文件:SubscriptionServiceFollowsPost.java   
@SuppressWarnings("unchecked")
public JSONArray executeImpl(String userId, WebScriptRequest req, WebScriptResponse res) throws IOException,
        ParseException
{
    JSONArray jsonUsers = (JSONArray) JSONValue.parseWithException(req.getContent().getContent());

    JSONArray result = new JSONArray();

    for (Object o : jsonUsers)
    {
        String user = (o == null ? null : o.toString());
        if (user != null)
        {
            JSONObject item = new JSONObject();
            item.put(user, subscriptionService.follows(userId, user));
            result.add(item);
        }
    }

    return result;
}
项目:alfresco-remote-api    文件:SubscriptionServiceFollowPost.java   
public JSONObject executeImpl(String userId, WebScriptRequest req, WebScriptResponse res) throws IOException,
        ParseException
{
    JSONArray jsonUsers = (JSONArray) JSONValue.parseWithException(req.getContent().getContent());

    for (Object o : jsonUsers)
    {
        String user = (o == null ? null : o.toString());
        if (user != null)
        {
            subscriptionService.follow(userId, user);
        }
    }

    return null;
}
项目:alfresco-remote-api    文件:SubscriptionServicePrivateListPut.java   
public JSONObject executeImpl(String userId, WebScriptRequest req, WebScriptResponse res) throws IOException,
        ParseException
{
    JSONObject obj = (JSONObject) JSONValue.parseWithException(req.getContent().getContent());

    Object setPrivate = obj.get("private");

    if (setPrivate != null)
    {
        if (setPrivate.toString().equalsIgnoreCase("true"))
        {
            subscriptionService.setSubscriptionListPrivate(userId, true);
        } else if (setPrivate.toString().equalsIgnoreCase("false"))
        {
            subscriptionService.setSubscriptionListPrivate(userId, false);
        }
    }

    return super.executeImpl(userId, req, res);
}
项目:alfresco-remote-api    文件:SubscriptionServiceUnfollowPost.java   
public JSONObject executeImpl(String userId, WebScriptRequest req, WebScriptResponse res) throws IOException,
        ParseException
{
    JSONArray jsonUsers = (JSONArray) JSONValue.parseWithException(req.getContent().getContent());

    for (Object o : jsonUsers)
    {
        String user = (o == null ? null : o.toString());
        if (user != null)
        {
            subscriptionService.unfollow(userId, user);
        }
    }

    return null;
}
项目:BiglyBT    文件:JSONUtils.java   
/**
 * decodes JSON formatted text into a map.
 *
 * @return Map parsed from a JSON formatted string
 * <p>
 *  If the json text is not a map, a map with the key "value" will be returned.
 *  the value of "value" will either be an List, String, Number, Boolean, or null
 *  <p>
 *  if the String is formatted badly, null is returned
 */
public static Map decodeJSON(String json) {
    try {
        Object object = JSONValue.parse(json);
        if (object instanceof Map) {
            return (Map) object;
        }
        // could be : ArrayList, String, Number, Boolean
        Map map = new HashMap();
        map.put("value", object);
        return map;
    } catch (Throwable t) {
        Debug.out("Warning: Bad JSON String: " + json, t);
        return null;
    }
}
项目:FireAnt    文件:MongoHandler.java   
public MongoHandler(Socket client, Request req, MongoClient mongoconn) throws Exception {
    Object obj = JSONValue.parse(req.getContent());
    JSONObject jobj = (JSONObject)obj;
    System.out.println(req.getContent());
    if((database = (String)jobj.get("database")) == null) {
        throw new Exception("Database not specified");
    }
    if((collection = (String)jobj.get("collection")) == null){
        throw new Exception("Collection not specified");
    }
    if((operation = (String)jobj.get("operation")) == null){
        throw new Exception("Operation not specified");
    }
    data = (JSONObject)jobj.get("data");
    this.dbconn = mongoconn;

    mdb = dbconn.getDatabase(database);
    mcollection = mdb.getCollection(collection);
    this.client = client;
}
项目:ZooKeeper    文件:FileLoader.java   
String handleRequest(JsonRequest request) throws Exception
   {
String output = "";

String file = request.getString("path", "/");
JSONObject o = new JSONObject();
try {
    this.source.addSource(file);
    o.put("status", "OK");

} catch (Exception e) {
    o.put("status", "ERR");
    o.put("error",  e.toString());
}

return JSONValue.toJSONString(o);
   }
项目:leaf-snowflake    文件:Utils.java   
public static Map readCommandLineOpts() {
    Map ret = new HashMap();
    String commandOptions = System.getProperty("leaf.options");
    if (commandOptions != null) {
        String[] configs = commandOptions.split(",");
        for (String config : configs) {
            config = URLDecoder.decode(config);
            String[] options = config.split("=", 2);
            if (options.length == 2) {
                Object val = JSONValue.parse(options[1]);
                if (val == null) {
                    val = options[1];
                }
                ret.put(options[0], val);
            }
        }
    }
    return ret;
}
项目:Direct-File-Downloader    文件:JSONUtils.java   
/**
 * decodes JSON formatted text into a map.
 * 
 * @return Map parsed from a JSON formatted string
 * <p>
 *  If the json text is not a map, a map with the key "value" will be returned.
 *  the value of "value" will either be an List, String, Number, Boolean, or null
 *  <p>
 *  if the String is formatted badly, null is returned
 */
public static Map decodeJSON(String json) {
    try {
        Object object = JSONValue.parse(json);
        if (object instanceof Map) {
            return (Map) object;
        }
        // could be : ArrayList, String, Number, Boolean
        Map map = new HashMap();
        map.put("value", object);
        return map;
    } catch (Throwable t) {
        Debug.out("Warning: Bad JSON String: " + json, t);
        return null;
    }
}
项目:nomulus    文件:RequestModule.java   
@Provides
@JsonPayload
@SuppressWarnings("unchecked")
static Map<String, Object> provideJsonPayload(
    @Header("Content-Type") MediaType contentType,
    @Payload String payload) {
  if (!JSON_UTF_8.is(contentType.withCharset(UTF_8))) {
    throw new UnsupportedMediaTypeException(
        String.format("Expected %s Content-Type", JSON_UTF_8.withoutParameters()));
  }
  try {
    return (Map<String, Object>) JSONValue.parseWithException(payload);
  } catch (ParseException e) {
    throw new BadRequestException(
        "Malformed JSON", new VerifyException("Malformed JSON:\n" + payload, e));
  }
}
项目:essence    文件:DataIOWriteAnomaly.java   
public String getCause(Integer lookupID)
   {
//if (causes != null) {
//return this.causes.get(lookupID);
//}
WebResource webResource = client.resource(AnomalyDetectionConfiguration.ANOMALY_REST_URL_PREFIX + "/anomaly/causes/");
String ret = webResource.accept("application/json").get(String.class);
JSONArray retArray = new JSONArray();
retArray = (JSONArray)JSONValue.parse(ret);

this.causes = new HashMap();

for (int i = 0; i < retArray.size(); i++) {
    Object oneObj = retArray.get(i);
    JSONObject oneJObj = (JSONObject)oneObj;


    Integer id = Integer.parseInt(oneJObj.get("id").toString());
    String cause = oneJObj.get("cause").toString();
    this.causes.put(id, cause);
}

return this.causes.get(lookupID);
   }
项目:StreamProcessingInfrastructure    文件:FileLoader.java   
String handleRequest(JsonRequest request) throws Exception
   {
String output = "";

String file = request.getString("path", "/");
JSONObject o = new JSONObject();
try {
    this.source.addSource(file);
    o.put("status", "OK");

} catch (Exception e) {
    o.put("status", "ERR");
    o.put("error",  e.toString());
}

return JSONValue.toJSONString(o);
   }
项目:bigstreams    文件:FileLoader.java   
String handleRequest(JsonRequest request) throws Exception
   {
String output = "";

String file = request.getString("path", "/");
JSONObject o = new JSONObject();
try {
    this.source.addSource(file);
    o.put("status", "OK");

} catch (Exception e) {
    o.put("status", "ERR");
    o.put("error",  e.toString());
}

return JSONValue.toJSONString(o);
   }
项目:bigstreams    文件:FileLoader.java   
String handleRequest(JsonRequest request) throws Exception
   {
String output = "";

String file = request.getString("path", "/");
JSONObject o = new JSONObject();
try {
    this.source.addSource(file);
    o.put("status", "OK");

} catch (Exception e) {
    o.put("status", "ERR");
    o.put("error",  e.toString());
}

return JSONValue.toJSONString(o);
   }
项目:spf    文件:Properties.java   
public static String toString(Map<String, String> properties,
        boolean useOldVersion) {
    if (useOldVersion) {
        final StringBuilder sb = new StringBuilder();
        final Iterator<Entry<String, String>> iterator = properties
                .entrySet().iterator();
        while (iterator.hasNext()) {
            final Entry<String, String> property = iterator.next();
            sb.append(property.getKey());
            sb.append(OLD_KEY_VALUE_SEPARATOR);
            sb.append(property.getValue());
            if (iterator.hasNext()) {
                sb.append(OLD_PROPERTY_SEPARATOR_CHAR);
            }
        }
        return sb.toString();
    } else {
        return JSON_PREFIX + JSONValue.toJSONString(properties);
    }
}
项目:devwars.tv    文件:Reference.java   
public static boolean recaptchaValid(String response, String ip) {
    System.out.println("Testing recaptcha");

    try {
        HttpResponse httpResponse = Unirest.post("https://www.google.com/recaptcha/api/siteverify")
            .field("secret", Reference.getEnvironmentProperty("recaptchaPrivateKey"))
            .field("response", response)
            .field("remoteip", ip)
            .asString();

        JSONObject responseObject = (JSONObject) JSONValue.parse(httpResponse.getBody().toString());

        return responseObject.get("success") != null;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
项目:AGORA-DSM    文件:SensorWebInfrastructure.java   
/**
 * 
 * @param message
 * @return
 */
public static String traditionalSensor(String request) {

    try {


        Object obj = JSONValue.parse(request);

        JSONObject observation = (JSONObject)obj;

        String operation = observation.get("message").toString();

        if (operation.equals("registerSensor"))
            RegisterSensorV2.send(observation);
        else if (operation.equals("publishObservation"))
            PublishObservationV2.send(observation);
        else if (operation.equals("updateSensor"))
            UpdateSensorV2.send(observation);

        return operation;

    } catch (Exception e) {
        // TODO: handle exception
    }
    return null;
}
项目:TreysDoubleJump    文件:UpdateChecker.java   
public static Object[] getLastUpdate() {
      try {
          JSONArray versionsArray = (JSONArray) JSONValue.parseWithException(IOUtils.toString(new URL(String.valueOf(VERSION_URL)), "UTF-8"));
          String lastVersion = ((JSONObject) versionsArray.get(versionsArray.size() - 1)).get("name").toString();

          if ((Integer.parseInt(lastVersion.replaceAll("\\.","")) > (Integer.parseInt(TreysDoubleJump.getPlugin(TreysDoubleJump.class).getDescription().getVersion().replaceAll("\\.",""))))) {
              JSONArray updatesArray = (JSONArray) JSONValue.parseWithException(IOUtils.toString(new URL(String.valueOf(DESCRIPTION_URL)), "UTF-8"));
              String updateName = ((JSONObject) updatesArray.get(updatesArray.size() - 1)).get("title").toString();

              Object[] update = {lastVersion, updateName};
              return update;
          }
      }
      catch (Exception e) {
          return new String[0];
      }
return new String[0];
  }
项目:MagicLoot3    文件:CSCoreLibLoader.java   
private boolean connect() {
     try {
         final URLConnection connection = this.url.openConnection();
         connection.setConnectTimeout(5000);
         connection.addRequestProperty("User-Agent", "CS-CoreLib Loader (by mrCookieSlime)");
         connection.setDoOutput(true);

         final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         final JSONArray array = (JSONArray) JSONValue.parse(reader.readLine());
         download = new URL((String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl"));
         file = new File("plugins/" + (String) ((JSONObject) array.get(array.size() - 1)).get("name") + ".jar");

         return true;
     } catch (IOException e) {
        System.err.println(" ");
        System.err.println("#################### - FATAL ERROR - ####################");
System.err.println(" ");
System.err.println("Could not connect to BukkitDev, is it down?");
System.err.println(" ");
System.err.println("#################### - FATAL ERROR - ####################");
System.err.println(" ");
         return false;
     }
 }
项目:release-maven-plugin-parent    文件:GitRepository.java   
@Override
public ProposedTag fromRef(final Ref gitTag) throws SCMException {
    notNull(gitTag, "gitTag");

    final RevWalk walk = new RevWalk(getGit().getRepository());
    final ObjectId tagId = gitTag.getObjectId();
    JSONObject message;
    try {
        final RevTag tag = walk.parseTag(tagId);
        message = (JSONObject) JSONValue.parse(tag.getFullMessage());
    } catch (final IOException e) {
        throw new SCMException(e, "Error while looking up tag because RevTag could not be parsed! Object-id was %s",
                tagId);
    } finally {
        walk.dispose();
    }
    if (message == null) {
        message = new JSONObject();
        message.put(VERSION, "0");
        message.put(BUILD_NUMBER, "0");
    }
    return new GitProposedTag(getGit(), log, gitTag, stripRefPrefix(gitTag.getName()), message,
            config.getRemoteUrlOrNull());
}
项目:nomulus    文件:RdapEntitySearchActionTest.java   
private Object generateExpectedJson(
    String handle,
    @Nullable String fullName,
    String status,
    @Nullable String email,
    @Nullable String address,
    String expectedOutputFile) {
  ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<>();
  builder.put("NAME", handle);
  if (fullName != null) {
    builder.put("FULLNAME", fullName);
  }
  if (email != null) {
    builder.put("EMAIL", email);
  }
  if (address != null) {
    builder.put("ADDRESS", address);
  }
  builder.put("TYPE", "entity");
  builder.put("STATUS", status);
  String substitutedFile = loadFile(this.getClass(), expectedOutputFile, builder.build());
  Object jsonObject = JSONValue.parse(substitutedFile);
  checkNotNull(jsonObject, "substituted file is not valid JSON: %s", substitutedFile);
  return jsonObject;
}
项目:DriveBackup    文件:DriveBackup.java   
/**
 * Checks if there is an available update (Adapted from Vault's update checker)
 *
 * @param currentVersion Current plugin version
 * @return Latest version
 */
public double updateCheck(double currentVersion) {
    try {
        URL url = new URL("https://api.curseforge.com/servermods/files?projectids=97321");
        URLConnection conn = url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("User-Agent", "DriveBackup Update Checker");
        conn.setDoOutput(true);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();
        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.getLogger().warning("No files found, or Feed URL is bad.");
            return currentVersion;
        }
        // Pull the last version from the JSON
        newVersionTitle = ((String) ((JSONObject) array.get(array.size() - 1)).get("name")).replace("DriveBackup-", "").trim();
        return Double.valueOf(newVersionTitle.replaceFirst("\\.", "").trim());
    } catch (Exception e) {
        MessageUtil.sendConsoleMessage("There was an issue attempting to check for the latest version.");
    }
    return currentVersion;
}
项目:trivolous    文件:Facebook.java   
public FbLoginInfo authFacebookLogin(String accessToken) {
FbLoginInfo fbLoginInfo = null;
      try {
        JSONObject jsonmap = (JSONObject) JSONValue.parse(
                readURL(new URL("https://graph.facebook.com/me?access_token=" + accessToken)));
        fbLoginInfo = new FbLoginInfo(); 
        fbLoginInfo.id = (String)jsonmap.get("id");
        fbLoginInfo.firstName = (String)jsonmap.get("first_name");
        fbLoginInfo.lastName = (String)jsonmap.get("last_name");
        fbLoginInfo.email = (String)jsonmap.get("email");
        logger.info("Facebook login : id=" + fbLoginInfo.id + " fname=" + fbLoginInfo.firstName + " lastname=" + 
                fbLoginInfo.lastName + " email=" + fbLoginInfo.email);
      } catch (Throwable ex) {
          logger.warn("Facebook login failed for token " + accessToken);
      }
      return fbLoginInfo;
  }
项目:AngryProgrammers    文件:Proxy.java   
@Override
public void onMessage(WebSocket conn, String message) {
    JSONArray j = (JSONArray) JSONValue.parse(message);
    Long id = (Long) j.get(0);
    JSONObject data = (JSONObject) j.get(1);

    ProxyResult<?> result = results.get(id);

    if (result != null) {
        results.remove(id);
        try {
            result.queue.put(result.message.gotResponse(data));
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
    }
}
项目:CS-CoreLib    文件:CSCoreLibLoader.java   
private boolean connect() {
     try {
         final URLConnection connection = this.url.openConnection();
         connection.setConnectTimeout(5000);
         connection.addRequestProperty("User-Agent", "CS-CoreLib Loader (by mrCookieSlime)");
         connection.setDoOutput(true);

         final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         final JSONArray array = (JSONArray) JSONValue.parse(reader.readLine());
         download = traceURL(((String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl")).replace("https:", "http:"));
         file = new File("plugins/" + (String) ((JSONObject) array.get(array.size() - 1)).get("name") + ".jar");

         return true;
     } catch (IOException e) {
        System.err.println(" ");
        System.err.println("#################### - WARNING - ####################");
System.err.println(" ");
System.err.println("Could not connect to BukkitDev.");
System.err.println("Please download & install CS-CoreLib manually:");
System.err.println("https://dev.bukkit.org/projects/cs-corelib");
System.err.println(" ");
System.err.println("#################### - WARNING - ####################");
System.err.println(" ");
         return false;
     }
 }
项目:teamcity-oauth    文件:OAuthClient.java   
public String getAccessToken(String code) throws IOException {
    RequestBody formBody = new FormBody.Builder()
            .add("grant_type", "authorization_code")
            .add("code", code)
            .add("redirect_uri", properties.getRootUrl())
            .add("client_id", properties.getClientId())
            .add("client_secret", properties.getClientSecret())
            .build();

    Request request = new Request.Builder()
            .url(properties.getTokenEndpoint())
            .addHeader("Accept", MediaType.APPLICATION_JSON_VALUE)
            .post(formBody)
            .build();
    Response response = getHttpClient().newCall(request).execute();
    Map jsonResponse = (Map) JSONValue.parse(response.body().string());
    return (String) jsonResponse.get("access_token");
}
项目:ChatChannels    文件:UpdateHandler.java   
/**
 * Queries the SpiGet servers and retrieves the latest release information (if current plugin version is outdated.)
 *
 * @return The updated version number [0], and update title [1] of the resource update
 */
public Object[] getLatestUpdate()
{
    try
    {
        JSONArray versions = (JSONArray) JSONValue.parseWithException(IOUtils.toString(new URL(String.valueOf(VERSION_URL))));
        String latestVersion = ((JSONObject) versions.get(versions.size() - 1)).get("name").toString();

        int remoteVersionNumber = Integer.parseInt(latestVersion.replaceAll("\\D+", ""));
        int localVersionNumber = Integer.parseInt(ChatChannels.get().getDescription().getVersion().replaceAll("\\D+", ""));

        System.out.println("[ChatChannels] Checking for updates... Remote version number: " + remoteVersionNumber);
        System.out.println("[ChatChannels] Checking for updates... Local version number: " + localVersionNumber);

        if (remoteVersionNumber > localVersionNumber)
        {
            JSONArray updates = (JSONArray) JSONValue.parseWithException(IOUtils.toString(new URL(DESCRIPTION_URL)));
            String latestUpdate = ((JSONObject) updates.get(updates.size() - 1)).get("title").toString();

            return new Object[]{latestVersion, latestUpdate};
        }
        else
            return null;

    }
    catch (ParseException | IOException e)
    {
        e.printStackTrace();
    }

    return null;
}
项目:jbake-rtl-jalaali    文件:MarkupEngine.java   
/**
 * Process the header of the file.
 * @param config 
 *
 * @param contents Contents of file
 * @param content
 */
private void processHeader(Configuration config, List<String> contents, final Map<String, Object> content) {
    for (String line : contents) {
        if (line.equals(HEADER_SEPARATOR)) {
            break;
        }

        if (line.isEmpty()) {
            continue;
        }

        String[] parts = line.split("=",2);
        if (parts.length != 2) {
            continue;
        }

        String key = parts[0].trim();
        String value = parts[1].trim();

        if (key.equalsIgnoreCase(Crawler.Attributes.DATE)) {
            DateFormat df = new SimpleDateFormat(config.getString(Keys.DATE_FORMAT));
            Date date = null;
            try {
                date = df.parse(value);
                content.put(key, date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else if (key.equalsIgnoreCase(Crawler.Attributes.TAGS)) {
            content.put(key, getTags(value));
        } else if (isJson(value)) {
            content.put(key, JSONValue.parse(value));
        } else {
            content.put(key, value);
        }
    }
}
项目:uppercore    文件:SpigetUpdateChecker.java   
public Object jsonQuery(String postfix) throws IOException {
    URL url = new URL(SITE_PREFIX + spigetId + postfix);
    URLConnection conn = url.openConnection();
    conn.setRequestProperty("User-Agent", USER_AGENT);
    if(((HttpURLConnection)conn).getResponseCode() == 404)
        return null;
    return JSONValue.parse(new InputStreamReader((InputStream)conn.getContent()));
}
项目:incubator-netbeans    文件:SourceMap.java   
/**
 * Parses the given {@code text} and returns the corresponding JSON object.
 * 
 * @param text text to parse.
 * @return JSON object that corresponds to the given text.
 * @throws IllegalArgumentException when the given text is not a valid
 * representation of a JSON object.
 */
private static JSONObject toJSONObject(String text) throws IllegalArgumentException {
    try {
        JSONObject json = (JSONObject)JSONValue.parseWithException(text);
        return json;
    } catch (ParseException ex) {
        throw new IllegalArgumentException(text);
    }
}
项目:incubator-netbeans    文件:WebKitDebuggingTransport.java   
@Override
public Void call(final String p) {
    RP.post(new Runnable() {
        @Override
        public void run() {
            try {
                JSONObject json = (JSONObject)JSONValue.parseWithException(p);
                responseCallback.handleResponse(new Response(json));
            } catch (ParseException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });
    return null;
}