Java 类net.sf.json.JSONException 实例源码

项目:jmeter-bzm-plugins    文件:BlazeMeterHttpUtils.java   
@Override
protected String extractErrorMessage(String response) {
    if (response != null && !response.isEmpty()) {
        try {
            JSON jsonResponse = JSONSerializer.toJSON(response, new JsonConfig());
            if (jsonResponse instanceof JSONObject) {
                JSONObject object = (JSONObject) jsonResponse;
                JSONObject errorObj = object.getJSONObject("error");
                if (errorObj.containsKey("message")) {
                    return errorObj.getString("message");
                }
            }
        } catch (JSONException ex) {
            log.debug("Cannot parse JSON error response: " + response);
        }
    }
    return response;
}
项目:private-WeChat    文件:CommonUtil.java   
/**
 * 获取access_token
 * 
 * @return
 * @deprecated
 */
public static Token getAccessToken(String appid, String appsecret) {
    Token accessToken = null;

    String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
    logger.info("获取access_token的请求url:{}", requestUrl);
    JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);

    // 如果请求成功
    if (null != jsonObject) {
        try {
            accessToken = new Token();
            accessToken.setToken(jsonObject.getString("access_token"));
            accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
        } catch (JSONException e) {
            accessToken = null;
            // 获取token失败
            logger.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
        }
    }
    return accessToken;
}
项目:osmp    文件:JSONUtils.java   
public static Map<String, String> jsonString2Map(String jsonStr) {
    JSONObject json_obj = null;
    try {
        json_obj = JSONObject.fromObject(jsonStr);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (json_obj == null)
        return null;
    Set<String> obj_keys = json_obj.keySet();
    if (obj_keys == null)
        return null;
    Map<String, String> map = new HashMap<String, String>();
    for (String item_key : obj_keys) {
        map.put(item_key, json_obj.getString(item_key));
    }
    return map;
}
项目:osmp    文件:JSONUtils.java   
/**
 * 
 * @param jsonStr
 *            需转换的标准的json字符串
 * @param clz
 *            转换对象
 * @param classMap
 *            转换对象中包含复杂对象,key对应jsonStr中key,value对应需转换为的复杂对象
 * @return
 */
public static <T> T jsonString2Bean(String jsonStr, Class<T> clz, Map<String, Class<?>> classMap) {
    JSONObject json_obj = null;
    try {
        json_obj = JSONObject.fromObject(jsonStr);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (json_obj == null)
        return null;
    JsonConfig config = new JsonConfig();
    config.setRootClass(clz);
    config.setClassMap(classMap);
    config.setHandleJettisonEmptyElement(true);
    return (T) JSONObject.toBean(json_obj, config);
}
项目:helicalinsight    文件:ResourceSecurityRule.java   
/**
 * Returns <code>true</code> if the file has matching security details. The credentials are
 * compared with the currently logged in user's credentials.
 *
 * @param fileAsJson The file under concern with extension from setting.xml
 * @return <code>true</code> if the file has matching security details.
 */
@Override
public boolean validate(JSONObject fileAsJson) {
    try {
        if (!"true".equalsIgnoreCase(fileAsJson.getString("visible"))) {
            return false;
        }
        Object unDeterminedObject = fileAsJson.get("security");
        if (unDeterminedObject instanceof JSONObject) {
            return RulesUtils.validateUser(AuthenticationUtils.getUserDetails(), (JSONObject) unDeterminedObject);
        } else {
            String security = fileAsJson.getString("security");
            return RulesUtils.validateUser(AuthenticationUtils.getUserDetails(), security);
        }
    } catch (JSONException ex) {
        logger.error("The resource is malformed. Setting.xml is configured to apply rules. " +
                "But the resource does not support " + "the rules.", ex);
    }
    return false;
}
项目:helicalinsight    文件:DirectoryLoader.java   
/**
 * Prepares the member variable visibleExtensionsMap
 *
 * @param visibleExtensions The JSON from the setting.xml for which the visible attribute
 *                          is provided to be true
 */
private void prepareExtensionsMap(JSONObject visibleExtensions) {
    Assert.notNull(visibleExtensions, "Visible extension's JSON is null!");
    Iterator<?> iterator = visibleExtensions.keys();
    this.visibleExtensionsMap = new HashMap<>();
    while (iterator.hasNext()) {
        int counter = 0;
        String key = (String) iterator.next();
        try {
            iterate(visibleExtensions, counter, key);
        } catch (JSONException ex) {
            // If the key is not a JSON object move to the next key
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("List of visible extensions that will be viewable " +
                "in the repository is " +
                visibleExtensionsMap);
    }
}
项目:helicalinsight    文件:DirectoryLoader.java   
/**
 * Prepares the member variables foldersTagMap and generic rules related
 * member variables
 *
 * @param visibleExtensions The JSON from the setting.xml for which the visible attribute
 *                          is provided to be true
 */
private void prepareFoldersTagMap(JSONObject visibleExtensions) {
    Assert.notNull(visibleExtensions, "Visible extension's JSON is null!");
    try {
        JSONObject foldersJSONObject = initialize(visibleExtensions);
        /*
         * genericRulesJSON has been prepared. Now prepare the foldersTagMap
*/
        prepareTextAndRuleValuesList(foldersJSONObject);
    } catch (JSONException ignore) {
    }

    if (logger.isDebugEnabled()) {
        logger.debug("The configured folder rule setting is " + foldersTagMap);
    }
}
项目:helicalinsight    文件:DirectoryLoader.java   
/**
 * Sets the booleans related to generic rules, prepares the genericRulesArray or
 * genericRulesJSON accordingly.
 * Returns the foldersTagMap.
 *
 * @param visibleExtensions The JSON from the setting.xml for which the visible attribute is
 *                          provided to be true
 * @return JSONObject of folder tag in setting.xml
 */
private JSONObject initialize(JSONObject visibleExtensions) {
    JSONObject foldersJSONObject = visibleExtensions.getJSONObject("folder");
    this.foldersTagMap = new HashMap<>();
    useFolderRules = true;
    try {
        genericRulesJSONArray = foldersJSONObject.getJSONArray("generic");
        isGenericRulePresent = true;
        multipleGenericRules = true;
    } catch (JSONException ex) {
        try {
            genericRulesJSON = new JSONObject();
            genericRulesJSON.accumulate("generic", foldersJSONObject.getString("generic"));
        } catch (JSONException ignore) {
        }
    }
    return foldersJSONObject;
}
项目:helicalinsight    文件:ConfigurableRulesHelper.java   
private static List<String> getRules(List<String> rules, JSONObject rulesJson) {
    try {
        rules.add(0, rulesJson.getJSONObject("rule").getString("@class"));
    } catch (JSONException ex) {
        try {
            JSONArray rulesArray = rulesJson.getJSONArray("rule");
            Iterator<?> iterator = rulesArray.iterator();
            //noinspection WhileLoopReplaceableByForEach
            while (iterator.hasNext()) {
                rules.add(((JSONObject) iterator.next()).getString("@class"));
            }
        } catch (Exception e) {
            throw new XmlConfigurationException("The configuration of setting.xml is " +
                    "incorrect. Expected class attribute(s) for the rules node child node(s) " +
                    "of security tag.", e);
        }
    }
    return rules;
}
项目:helicalinsight    文件:JsonUtils.java   
/**
 * This method is used to get the extension for the file which need to be
 * create
 *
 * @return String
 */
public static String getEfwResultExtension() {
    JSONObject settingsJson = getSettingsJson();
    String extension = null;
    try {
        JSONObject extensionsJSONObject = settingsJson.getJSONObject("Extentions").getJSONObject("efwresult");
        if (extensionsJSONObject == null) {
            throw new ApplicationException();
        }
        extension = extensionsJSONObject.getString("#text");
    } catch (JSONException ex) {
        logger.error("Please provide attribute visible to be true in the Extensions tag for " + "efwresult", ex);
    } catch (ApplicationException e) {
        logger.error("The object extensionsJSONObject is null.");
    }
    return extension;
}
项目:helicalinsight    文件:JsonUtils.java   
/**
 * <p>
 * Obtains the efwsr file extension from the setting.xml file
 * </p>
 *
 * @return A string that is the key value of efwsr in setting.xml
 */
public static String getEFWSRExtension() {
    ApplicationProperties properties = ApplicationProperties.getInstance();
    IProcessor processor = ResourceProcessorFactory.getIProcessor();
    JSONObject json = processor.getJSONObject(properties.getSettingPath(), false);

    String extension = null;
    try {
        JSONObject extensionsJSONObject = json.getJSONObject("Extentions").getJSONObject("efwsr");
        if (extensionsJSONObject == null) {
            throw new ApplicationException();
        }
        extension = extensionsJSONObject.getString("#text");
    } catch (JSONException ex) {
        logger.error("Please provide attribute visible to be true in the Extensions tag for " + "efwsr", ex);
    } catch (ApplicationException e) {
        logger.error("The object extensionsJSONObject is null.");
    }
    return extension;
}
项目:helicalinsight    文件:JsonUtils.java   
/**
 * <p>
 * Gets efwFolder key value from setting.xml. If it is not present in
 * setting.xml, it will throw exception else return value of efwFolder node.
 * </p>
 *
 * @return a <code>String</code> which specifies value of efwFolder node in
 * setting.xml
 */
public static String getFolderFileExtension() {
    ApplicationProperties applicationProperties = ApplicationProperties.getInstance();
    IProcessor processor = ResourceProcessorFactory.getIProcessor();
    JSONObject json = processor.getJSONObject(applicationProperties.getSettingPath(), false);

    String extension = null;
    try {
        JSONObject extensionsJSONObject = json.getJSONObject("Extentions").getJSONObject("folder").getJSONObject
                ("efwFolder");
        if (extensionsJSONObject == null) {
            throw new ImproperXMLConfigurationException("Setting.xml configuration is " + "incorrect");
        }
        extension = extensionsJSONObject.getString("#text");
    } catch (JSONException ex) {
        logger.error("Exception while retrieving efwFolder key's value", ex);
    } catch (ImproperXMLConfigurationException e) {
        logger.error("ImproperXMLConfigurationException", e);
    }
    return extension;
}
项目:helicalinsight    文件:ExecuteReport.java   
/**
 * <p>
 * The parameters in the templateData will be replaced with the
 * corresponding values from the parametersJSON
 * </p>
 *
 * @param templateData   The content of the template file as string
 * @param parametersJSON The json of the parameters
 * @return Updated template html file as string
 */
String replaceParameters(String templateData, JSONObject parametersJSON) {
    Iterator<?> keys = parametersJSON.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        if (templateData.contains("${" + key + "}")) {
            try {
                JSONArray array = parametersJSON.getJSONArray(key);
                String value = array.toString();
                logger.debug("value = " + value);
                value = value.replace("[", "").replace("]", "").replace("\"", "'");
                logger.debug("The value for key " + key + "is " + value);
                templateData = templateData.replace("${" + key + "}", value);
            } catch (JSONException ex) {
                logger.debug("key " + key + "is not an array" + ". Key value = " +
                        parametersJSON.getString(key));
                templateData = templateData.replace("${" + key + "}", parametersJSON.getString(key));
            }
        }
    }
    return templateData;
}
项目:helicalinsight    文件:ApplicationUtilities.java   
/**
 * <p>
 * This method creates net.sf.Json.JSONArray using List of Maps
 * </p>
 *
 * @param listOfMaps a list of map objects
 * @return a <code>String</code> which is a JSONArray.
 */
public static JSONArray getJSONArray(List<Map<String, String>> listOfMaps) {
    JSONArray jsonArray = new JSONArray();
    for (Map<String, String> map : listOfMaps) {
        JSONObject jsonObject = new JSONObject();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            try {
                jsonObject.put(key, value);
            } catch (JSONException e) {
                logger.error("JSONException", e);
            }
        }
        jsonArray.add(jsonObject);
    }
    return jsonArray;
}
项目:helicalinsight    文件:FileOperationsUtility.java   
/**
 * Deletes the specified favourite file
 *
 * @param reportFile      The name of the file
 * @param reportDirectory The location of reportFile
 */
public void deleteFavouriteFile(String reportFile, String reportDirectory) {
    File xmlFile = new File(this.solutionDirectory + File.separator + reportDirectory + File.separator +
            reportFile);
    IProcessor processor = ResourceProcessorFactory.getIProcessor();
    JSONObject jsonObject = processor.getJSONObject(xmlFile.toString(), false);

    try {
        String fileTobeSearched = jsonObject.getString("favourite");
        logger.info("Trying to delete the file " + fileTobeSearched);
        boolean result = deleteFile(this.solutionDirectory, fileTobeSearched);
        logger.debug("File " + fileTobeSearched + " deleted status " + result);
    } catch (JSONException ex) {
        logger.error("JSONException", ex);
    }
}
项目:helicalinsight    文件:DeleteOperationHandler.java   
/**
 * Validates the request parameter sourceArray
 *
 * @param sourceArray The request parameter sourceArray
 * @return true if validated
 */
private boolean isSourceArrayValid(String sourceArray) {
    JSONArray sourceJSON;
    try {
        sourceJSON = (JSONArray) JSONSerializer.toJSON(sourceArray);
    } catch (JSONException ex) {
        logger.error("JSONException : " + ex);
        return false;
    }
    if (!prepareLists(sourceJSON)) {
        throw new OperationFailedException("The requested resource(s) do not exist in the " + "repository. " +
                "Aborting operation.");
    }
    extensionsList = getListOfExtensionsFromSettings();
    return (extensionsList != null);
}
项目:helicalinsight    文件:IOOperationsUtility.java   
/**
 * Iterates over the given jsonObject and prepares a key value paris map
 *
 * @param jsonObject The json of the extensions tag from setting.xml
 * @return A <code>Map<String, String></code> which is created from
 * JSONObject.
 */
private Map<String, String> populateMap(JSONObject jsonObject) {
    Map<String, String> map = new HashMap<>();
    Iterator<?> iterator;
    if (jsonObject != null) {
        iterator = jsonObject.keys();
    } else {
        throw new RuntimeException("The jsonObject is null.");
    }

    if (iterator != null) {
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            try {
                map.put(jsonObject.getJSONObject(key).getString("#text"), key);
            } catch (JSONException ex) {
                logger.info("No rule or text value for the key " + key + " is provided.");
            }
        }
    }
    return map;
}
项目:helicalinsight    文件:FileArchive.java   
/**
 * Obtains the extension of the zip file from setting.xml
 *
 * @return returns the efwExport key value from the setting.xml
 */

public String getExtensionOfZipFile() {
    ApplicationProperties properties = ApplicationProperties.getInstance();
    IProcessor processor = ResourceProcessorFactory.getIProcessor();
    JSONObject json = processor.getJSONObject(properties.getSettingPath(), false);

    String extension = null;
    try {
        extension = json.getJSONObject("Extentions").getString("efwExport");
        if (extension == null) {
            throw new ApplicationException();
        }
        logger.debug("efwExport text value = " + extension);
    } catch (JSONException ex) {
        logger.error("Please provide efwExport tag in Extensions of settings", ex);
    } catch (ApplicationException e) {
        logger.error("The extension is null.");
    }
    return extension;
}
项目:helicalinsight    文件:RenameOperationHandler.java   
/**
 * Converts the input into convenient format for the sake of processing
 *
 * @param sourceJSON The request parameter sourceArray's json
 * @return true if the the files in the sourceArray really exist so that
 * they can be renamed
 */
private boolean prepareMap(JSONArray sourceJSON) {
    Iterator<?> iterator = sourceJSON.iterator();
    try {
        while (iterator.hasNext()) {
            JSONArray jsonArray = (JSONArray) iterator.next();
            logger.debug("Set of original and new Names: jsonArray : " + jsonArray);
            if (!populateListOfMaps(listOfMaps, jsonArray)) {
                return false;
            }
        }
    } catch (JSONException ex) {
        logger.error("sourceArray is not an array of arrays", ex);
        return false;
    }
    logger.debug("List on which rename operations to be performed on " + listOfMaps);
    return true;
}
项目:helicalinsight    文件:EfwdReaderUtility.java   
public List<JSONObject> getAllEfwdConnections(String subType) {
    if (subType == null) {
        logger.debug("The subType parameter is null" +
                ". It is required to list the required type of data sources in " +
                "case of efwd. Reading all the data sources of all types.");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Received a request to read all the connections in all efwd files, " +
                "" + "which are accessible to the currently logged in user.");
    }

    Map<String, String> mapOfEfwds = prepareMapOfEfwd();
    List<JSONObject> connections = new ArrayList<>();
    Set<Map.Entry<String, String>> entries = mapOfEfwds.entrySet();
    for (Map.Entry<String, String> entry : entries) {
        String directory = entry.getKey();
        try {
            addEfwdConnectionsToList(directory, entry.getValue(), connections, subType);
        } catch (JSONException ignore) {
            logger.error("A file named " + directory + " has improper xml file of efwd. The " +
                    "exception is ", ignore);
        }
    }
    return connections;
}
项目:marathon-plugin    文件:TokenAuthProvider.java   
/**
 * Helper method to update a credential stored within the Jenkins Credential Store. This creates a new credential
 * to replace tokenCredentials.
 *
 * @param tokenCredentials The current, existing credential to update.
 * @param token            New token value for credential
 * @return New Credentials constructed from tokenCredentials
 */
StringCredentials newTokenCredentials(final StringCredentials tokenCredentials, final String token) {
    // retrieved a new token, now to update the existing credential in `tokenCredentials`
    JSONObject json;
    try {
        json = JSONObject.fromObject(tokenCredentials.getSecret().getPlainText());
    } catch (JSONException jse) {
        json = new JSONObject();
    }
    json.put("jenkins_token", token);

    return new StringCredentialsImpl(
            tokenCredentials.getScope(),
            tokenCredentials.getId(),
            tokenCredentials.getDescription(),
            Secret.fromString(json.toString()));
}
项目:marathon-plugin    文件:MarathonBuilderImpl.java   
/**
 * Get a Marathon client with Authorization headers using the token within provided credentials. If the content of
 * credentials is JSON, this will use the "jenkins_token" field; if the content is just a string, that will be
 * used as the token value.
 *
 * @param credentials String credentials
 * @return Marathon client with token in auth header
 */
private Marathon getMarathonClient(StringCredentials credentials) {
    String token;

    try {
        final JSONObject json = JSONObject.fromObject(credentials.getSecret().getPlainText());
        if (json.has("jenkins_token")) {
            token = json.getString("jenkins_token");
        } else {
            token = "";
        }
    } catch (JSONException jse) {
        token = credentials.getSecret().getPlainText();
    }

    if (StringUtils.isNotEmpty(token)) {
        return MarathonClient
                .getInstanceWithTokenAuth(getURL(), token);
    }

    return getMarathonClient();
}
项目:CI-Jenkins-Plugin    文件:GitHubPullRequestHelper.java   
private Map<String, Object> toMap(JSONObject object) throws JSONException {
  Map<String, Object> map = new HashMap<String, Object>();
  Iterator<String> keysItr = object.keySet().iterator();
  while (keysItr.hasNext()) {
    String key = keysItr.next();
    Object value = object.get(key);

    if (value instanceof JSONArray) {
      value = toList((JSONArray) value);
    } else if (value instanceof JSONObject) {
      value = toMap((JSONObject) value);
    }
    map.put(key, value);
  }
  return map;
}
项目:CI-Jenkins-Plugin    文件:JSONUtil.java   
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
  Map<String, Object> map = new HashMap<String, Object>();
  Iterator<String> keysItr = object.keySet().iterator();
  while (keysItr.hasNext()) {
    String key = keysItr.next();
    Object value = object.get(key);

    if (value instanceof JSONArray) {
      value = toList((JSONArray) value);
    } else if (value instanceof JSONObject) {
      value = toMap((JSONObject) value);
    }
    map.put(key, value);
  }
  return map;
}
项目:GitRobot    文件:GitRobot.java   
private void writeFileFromGitUrl(String strGitUrl, String strFileName){
    try {
        File file = new File(strFileName);
        File dir = file.getParentFile();
        if(!dir.exists())
            dir.mkdirs();
        String strJSON = getDataFromUrl(strGitUrl);
        JSONObject jsonObj = (JSONObject)JSONSerializer.toJSON(strJSON);
        if(jsonObj.has("content")){
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] decodeData = decoder.decodeBuffer(jsonObj.getString("content"));
            FileOutputStream os = new FileOutputStream(file);
            os.write(decodeData);
            os.close();
        }

        System.out.println("Downloaded!\t" + strFileName);
    }catch(JSONException ex){
        System.out.println("JSON Parse Error: " + ex.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("Write File Error: " + e.getMessage());
    }
}
项目:GitRobot    文件:GitRobot.java   
/**
 * ������Ϣ����
 * @param strMsg ������Ϣ
 * @return void
 */
private void errHandle(String strMsg){
    try{
        JSONObject jsonObj = (JSONObject)JSONSerializer.toJSON(strMsg);
        String msg = jsonObj.getString("message");
        String strErrorMsg = "Error: " + msg +". ";
        if(jsonObj.has("errors")){
            JSONArray errArray = jsonObj.getJSONArray("errors");
            Iterator<JSONObject> it = errArray.iterator();
            while(it.hasNext()){
                JSONObject errObj = it.next();
                if(errObj.has("message"))
                    strErrorMsg += errObj.getString("message")+". ";
            }
        }
        System.out.println(strErrorMsg);
    }catch(JSONException ex){
        //ex.printStackTrace();
        System.out.println("Error: " + strMsg);
    }
}
项目:logsniffer    文件:DailyRollingLogAccess.java   
@Override
public LogPointer getFromJSON(final String data) throws IOException {
    try {
        final JSONObject json = JSONObject.fromObject(data);
        if (json.size() > 0) {
            final RollingLogPointer rlp = new RollingLogPointer(json.getString("p"), new String[] {},
                    new DefaultPointer(0, 0), json.getBoolean("f"), json.getBoolean("l"));
            rlp.allLogsHash = json.getInt("h");
            rlp.liveNext = json.optString("n", null);
            final PointerData spd = getLogIndex(rlp);
            if (spd.pointer != null) {
                rlp.filePointer = getPartLogAccess(parts[spd.index])
                        .getFromJSON(json.getJSONObject("u").toString());
            }
            return createRelative(rlp, 0);
        } else {
            return createRelative(null, 0);
        }
    } catch (final JSONException e) {
        LOGGER.warn("Invalid JSON pointer: " + data, e);
        return createRelative(null, 0);
    }
}
项目:mobile-starting-framework    文件:CXFReportingService.java   
@POST
@Path("getRevisionsById")
public List<Submission> getRevisionsById(@RequestBody String data) {
    if (data == null) {
        return null;
    }
    JSONObject queryParams;
    try {
        queryParams = (JSONObject) JSONSerializer.toJSON(data);
        //test
        return testSubmissions();
        //end test
        //return getDao().findAllSubmissionsByParentId(queryParams.getLong("id"));
    } catch (JSONException je) {
        LOG.error("JSONException in :" + data + " : " + je.getMessage());
        return null; //and more sadness
    }
}
项目:mobile-starting-framework    文件:CXFAcademicsService.java   
@POST
@Path("/getCareers")
public List<Career> getCareers(@RequestBody String data) {
    if (data == null) {
        return null; //and sadness
    }

    JSONObject queryParams;
    try {
        queryParams = (JSONObject) JSONSerializer.toJSON(data);
    } catch (JSONException je) {
        LOG.error("JSONException in :" + data + " : " + je.getMessage());
        return null; //and more sadness
    }
    Map<String, String> query = new HashMap<String, String>();
    query.put(AcademicsConstants.TERM_ID, queryParams.getString("termId"));
    return getDao().getCareers(query);
}
项目:mobile-starting-framework    文件:CXFAcademicsService.java   
@POST
@Path("/getSubjects")
public List<Subject> getSubjects(@RequestBody String data) {
    if (data == null) {
        return null; //and sadness
    }

    JSONObject queryParams;
    try {
        queryParams = (JSONObject) JSONSerializer.toJSON(data);
    } catch (JSONException je) {
        LOG.error("JSONException in :" + data + " : " + je.getMessage());
        return null; //and more sadness
    }
    Map<String, String> query = new HashMap<String, String>();
    query.put(AcademicsConstants.TERM_ID, queryParams.getString("termId"));
    query.put(AcademicsConstants.CAREER_ID, queryParams.getString("careerId"));
    List<Subject> subjects = getDao().getSubjects(query);
    return subjects;
}
项目:mobile-starting-framework    文件:AcademicsServiceImpl.java   
@Override
@POST
@Path("/classSearch")
public SearchResult getClassSearchResults(@RequestBody String data) {

    if (data == null) {
        return null;
    }

    Map<String, String[]> queryParams;
    JSONObject jsonObject;
    try {
        jsonObject = (JSONObject) JSONSerializer.toJSON(data);

        queryParams = toMap(jsonObject);

    } catch (JSONException je) {
        LOG.error("JSONException in :" + data + " : " + je.getMessage());
        return null; //and more sadness
    }

    //LOG.debug(queryParams);

    SearchResult result = getDao().getSearchResults(queryParams);
    return result;
}
项目:gerrit-events    文件:GerritJsonEventFactory.java   
/**
 * Returns the value of a JSON property as a Date if it exists otherwise returns the defaultValue.
 * @param json the JSONObject to check.
 * @param key the key.
 * @param defaultValue the value to return if the key is missing.
 * @return the value for the key as a Date.
 */
public static Date getDate(JSONObject json, String key, Date defaultValue) {
    Date result = defaultValue;
    if (json.containsKey(key)) {
        try {
            String secondsString = json.getString(key);
            //In gerrit, time is written in seconds, not milliseconds.
            Long milliseconds = TimeUnit.SECONDS.toMillis(Long.parseLong(secondsString));
            result = new Date(milliseconds);
            // CS IGNORE EmptyBlockCheck FOR NEXT 2 LINES. REASON: result is already set to defaultValue.
        } catch (JSONException ex) {
        } catch (NumberFormatException nfe) {
        }
    }
    return result;
}
项目:geowave    文件:FeatureCountMinSketchStatistics.java   
/**
 * Convert FeatureCountMinSketch statistics to a JSON object
 */

public JSONObject toJSONObject()
        throws JSONException {
    JSONObject jo = new JSONObject();
    jo.put(
            "type",
            STATS_TYPE.getString());

    jo.put(
            "statisticsID",
            statisticsId.getString());

    jo.put(
            "field_identifier",
            getFieldName());

    jo.put(
            "size",
            sketch.size());

    return jo;
}
项目:geowave    文件:XZHierarchicalIndexStrategy.java   
/**
 * Convert XZHierarchical Index Metadata statistics to a JSON object
 */

@Override
public JSONObject toJSONObject()
        throws JSONException {
    JSONObject jo = new JSONObject();
    jo.put(
            "type",
            "XZHierarchicalIndexStrategy");

    jo.put(
            "pointCurveMultiDimensionalId",
            pointCurveMultiDimensionalId);
    jo.put(
            "xzCurveMultiDimensionalId",
            xzCurveMultiDimensionalId);
    jo.put(
            "pointCurveCount",
            pointCurveCount);
    jo.put(
            "xzCurveCount",
            xzCurveCount);

    return jo;
}
项目:geowave    文件:DifferingFieldVisibilityEntryCount.java   
/**
 * Convert Differing Visibility statistics to a JSON object
 */

public JSONObject toJSONObject()
        throws JSONException {
    JSONObject jo = new JSONObject();
    jo.put(
            "type",
            STATS_TYPE.getString());
    jo.put(
            "statisticsID",
            statisticsId.getString());
    jo.put(
            "count",
            entriesWithDifferingFieldVisibilities);
    return jo;
}
项目:geowave    文件:DuplicateEntryCount.java   
/**
 * Convert Duplicate Count statistics to a JSON object
 */

public JSONObject toJSONObject()
        throws JSONException {
    JSONObject jo = new JSONObject();
    jo.put(
            "type",
            STATS_TYPE.getString());

    jo.put(
            "statisticsID",
            statisticsId.getString());

    jo.put(
            "count",
            entriesWithDuplicates);

    return jo;
}
项目:geowave    文件:CountDataStatistics.java   
/**
 * Convert Count statistics to a JSON object
 */

public JSONObject toJSONObject()
        throws JSONException {
    JSONObject jo = new JSONObject();
    jo.put(
            "type",
            STATS_TYPE.getString());
    jo.put(
            "statisticsID",
            statisticsId.getString());
    jo.put(
            "count",
            count);
    return jo;
}
项目:geowave    文件:IndexMetaDataSet.java   
/**
 * Convert Index Metadata statistics to a JSON object
 */

public JSONObject toJSONObject()
        throws JSONException {
    JSONObject jo = new JSONObject();
    jo.put(
            "type",
            STATS_TYPE.getString());

    jo.put(
            "statisticsID",
            statisticsId.getString());

    JSONArray mdArray = new JSONArray();
    for (final IndexMetaData imd : this.metaData) {
        mdArray.add(imd.toJSONObject());
    }
    jo.put(
            "metadata",
            mdArray);

    return jo;
}
项目:upweatherframework    文件:UPWeatherRequest.java   
/**
 * This method retrieve the time series storing them in a UPTimeSeries object.
 * @return an UPTimeSeries object
 * @throws IOException if connection hangs.
 * @throws UPInvalidParameterException if invalid parameters are specified.
 * @throws NoSuchMethodException if internal errors occurs.
 * @throws IllegalAccessException if internal errors occurs.
 * @throws IllegalArgumentException if internal errors occurs.
 * @throws InvocationTargetException if internal errors occurs.
 */
public final UPTimeSeries getTimeSeries() throws IOException, UPInvalidParameterException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    this.setUrl("https://api.uniparthenope.it/meteo/timeseries");
    JSONArray timeSeriesArray;
    try {
        timeSeriesArray = this.connect().getJSONObject("timeseries").getJSONObject("timeseries").getJSONObject("places").getJSONObject("place").getJSONObject("runs").getJSONArray("run").getJSONObject(0).getJSONArray("time");
    } catch (JSONException exc) {
        return null;
    }
    JSONObject currentObject;
    UPTimeSeries series = new UPTimeSeries(timeSeriesArray.size());
    Set keys = UPForecast.HASH_METHODS.keySet();
    for (Object timeSeries : timeSeriesArray) {
        currentObject = (JSONObject) timeSeries;
        UPForecast forecast = this.parseJsonTimeSeries(currentObject, keys);
        series.addForecast(forecast);
    }
    return series;
}
项目:blazemeter-bamboo-plugin    文件:BambooBzmUtils.java   
@Override
protected String extractErrorMessage(String response) {
    if (response != null && !response.isEmpty()) {
        try {
            JSONObject jsonResponse = JSONObject.fromObject(response);
            JSONObject errorObj = jsonResponse.getJSONObject("error");
            if (errorObj.containsKey("message")) {
                return errorObj.getString("message");
            }
        } catch (JSONException ex) {
            logger.debug("Cannot parse response: " + response, ex);
            return "Cannot parse response: " + response;
        }
    }
    return null;
}