Java Code Examples for org.json.simple.JSONValue

The following are top voted examples for showing how to use org.json.simple.JSONValue. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: fuck_zookeeper   File: FileLoader.java   Source Code and License 12 votes vote down vote up
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);
   }
 
Example 2
Project: https-github.com-apache-zookeeper   File: FileLoader.java   Source Code and License 8 votes vote down vote up
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);
   }
 
Example 3
Project: Cognizant-Intelligent-Test-Scripter   File: Performance.java   Source Code and License 7 votes vote down vote up
/**
    * 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;
   }
 
Example 4
Project: FireAnt   File: MongoHandler.java   Source Code and License 7 votes vote down vote up
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;
}
 
Example 5
Project: ZooKeeper   File: FileLoader.java   Source Code and License 7 votes vote down vote up
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);
   }
 
Example 6
Project: StreamProcessingInfrastructure   File: FileLoader.java   Source Code and License 7 votes vote down vote up
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);
   }
 
Example 7
Project: SecureKeeper   File: FileLoader.java   Source Code and License 7 votes vote down vote up
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);
   }
 
Example 8
Project: incubator-netbeans   File: ScriptExecutorImpl.java   Source Code and License 6 votes vote down vote up
@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;
    }
}
 
Example 9
Project: Uranium   File: YUMCStatistics.java   Source Code and License 6 votes vote down vote up
/**
 * 发送服务器数据到统计网页
 */
private void postPlugin() throws IOException {
    // 服务器数据获取
    final String pluginname = Uranium.name;
    final String tmposarch = System.getProperty("os.arch");

    final Map<String, Object> data = new HashMap();
    data.put("guid", guid);
    data.put("server_version", Bukkit.getVersion());
    data.put("server_port", Bukkit.getServer().getPort());
    data.put("server_tps", FMLCommonHandler.instance().getMinecraftServerInstance().recentTps[1]);
    data.put("plugin_version", Uranium.getCurrentVersion());
    data.put("players_online", Bukkit.getServer().getOnlinePlayers().size());
    data.put("os_name", System.getProperty("os.name"));
    data.put("os_arch", tmposarch.equalsIgnoreCase("amd64") ? "x86_64" : tmposarch);
    data.put("os_version", System.getProperty("os.version"));
    data.put("os_usemem", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024);
    data.put("os_cores", Runtime.getRuntime().availableProcessors());
    data.put("auth_mode", Bukkit.getServer().getOnlineMode() ? 1 : 0);
    data.put("java_version", System.getProperty("java.version"));

    final String jsondata = "Info=" + JSONValue.toJSONString(data);

    final String url = String.format("http://api.yumc.pw/I/P/S/V/%s/P/%s", REVISION, URLEncoder.encode(pluginname, "UTF-8"));
    print("Plugin: " + pluginname + " Send Data To CityCraft Data Center");
    print("Address: " + url);
    print("Data: " + jsondata);
    // 发送数据
    final JSONObject result = (JSONObject) JSONValue.parse(postData(url, jsondata));
    print("Plugin: " + pluginname + " Recover Data From CityCraft Data Center: " + result.get("info"));
}
 
Example 10
Project: open-kilda   File: ServiceSwitchImpl.java   Source Code and License 6 votes vote down vote up
/**
 * get All Ports.
 *
 * @param switchId
 *            the switch id
 * @return List<PortInfo>
 */
public List<PortInfo> getPortResponseBasedOnSwitchId(String switchId) {

	log.info("Inside ServiceSwitchImpl method getPortResponseBasedOnSwitchId");
	List<PortInfo> switchPortsInfoList = new ArrayList<PortInfo>();
	ObjectMapper mapper = new ObjectMapper();
	String key = switchId;
	try {
		JSONObject jsonObject = switchIntegrationService.getSwitchPorts();
		log.info("getPortResponseBasedOnSwitchId GET_SWITCH_PORT_DATA_URL api call response is "
				+ jsonObject);

		if (jsonObject != null) {
			Object object = jsonObject.get(key);
			if (object != null) {
				String val = JSONValue.toJSONString(object);
				PortDetailResponse portDetailResponse = mapper.readValue(
						val, PortDetailResponse.class);

				List<PortDesc> portDescList = portDetailResponse
						.getPortDesc();
				if (portDescList != null && !portDescList.isEmpty()) {
					switchPortsInfoList = switchDataUtil.getSwitchPortInfo(
							portDescList, key, switchPortsInfoList);
				}
			}
		}
	} catch (Exception exception) {
		log.error("Exception in getPortResponseBasedOnSwitchId "
				+ exception.getMessage());
	}

	log.info("exit ServiceSwitchImpl method getPortResponseBasedOnSwitchId");
	return switchPortsInfoList;
}
 
Example 11
Project: ShowPolicyPackage   File: HtmlUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 12
Project: EmojiChat   File: EmojiChatUpdateChecker.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example 13
Project: Cognizant-Intelligent-Test-Scripter   File: Performance.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 14
Project: alfresco-remote-api   File: SubscriptionServiceFollowsPost.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 15
Project: alfresco-remote-api   File: SubscriptionServiceFollowPost.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 16
Project: alfresco-remote-api   File: SubscriptionServicePrivateListPut.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 17
Project: alfresco-remote-api   File: SubscriptionServiceUnfollowPost.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 18
Project: BiglyBT   File: JSONUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example 19
Project: ZooKeeper   File: FileLoader.java   Source Code and License 6 votes vote down vote up
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);
   }
 
Example 20
Project: leaf-snowflake   File: Utils.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 21
Project: Direct-File-Downloader   File: JSONUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example 22
Project: nomulus   File: RequestModule.java   Source Code and License 6 votes vote down vote up
@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));
  }
}
 
Example 23
Project: essence   File: DataIOWriteAnomaly.java   Source Code and License 6 votes vote down vote up
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);
   }
 
Example 24
Project: bigstreams   File: FileLoader.java   Source Code and License 6 votes vote down vote up
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);
   }
 
Example 25
Project: bigstreams   File: FileLoader.java   Source Code and License 6 votes vote down vote up
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);
   }
 
Example 26
Project: spf   File: Properties.java   Source Code and License 6 votes vote down vote up
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);
	}
}
 
Example 27
Project: devwars.tv   File: Reference.java   Source Code and License 6 votes vote down vote up
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;
    }
}
 
Example 28
Project: AGORA-DSM   File: SensorWebInfrastructure.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @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;
}
 
Example 29
Project: TreysDoubleJump   File: UpdateChecker.java   Source Code and License 6 votes vote down vote up
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];
  }
 
Example 30
Project: MagicLoot3   File: CSCoreLibLoader.java   Source Code and License 6 votes vote down vote up
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;
     }
 }
 
Example 31
Project: release-maven-plugin-parent   File: GitRepository.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 32
Project: nomulus   File: RdapEntitySearchActionTest.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 33
Project: DriveBackup   File: DriveBackup.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 34
Project: trivolous   File: Facebook.java   Source Code and License 6 votes vote down vote up
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;
  }
 
Example 35
Project: AngryProgrammers   File: Proxy.java   Source Code and License 6 votes vote down vote up
@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();
        }
    }
}
 
Example 36
Project: CS-CoreLib   File: CSCoreLibLoader.java   Source Code and License 6 votes vote down vote up
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;
     }
 }
 
Example 37
Project: teamcity-oauth   File: OAuthClient.java   Source Code and License 6 votes vote down vote up
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");
}
 
Example 38
Project: ChatChannels   File: UpdateHandler.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 39
Project: jbake-rtl-jalaali   File: MarkupEngine.java   Source Code and License 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 40
Project: uppercore   File: SpigetUpdateChecker.java   Source Code and License 5 votes vote down vote up
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()));
}