net.sf.json.JSONException Java Examples

The following examples show how to use net.sf.json.JSONException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: jmeter-bzm-plugins   Author: Blazemeter   File: BlazeMeterHttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #2
Source Project: marathon-plugin   Author: jenkinsci   File: MarathonBuilderImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #3
Source Project: zap-extensions   Author: zaproxy   File: HttpPanelJsonView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isEnabled(Message message) {
    String jsonString;
    if (message instanceof HttpMessage) {
        HttpMessage httpMessage = ((HttpMessage) message);
        if (this.model instanceof RequestBodyStringHttpPanelViewModel) {
            jsonString = httpMessage.getRequestBody().toString();
        } else if (this.model instanceof ResponseBodyStringHttpPanelViewModel) {
            jsonString = httpMessage.getResponseBody().toString();
        } else {
            return false;
        }
    } else {
        return false;
    }
    try {
        toJson(jsonString);
        return true;
    } catch (JSONException e) {
        return false;
    }
}
 
Example #4
Source Project: zap-extensions   Author: zaproxy   File: HttpPanelJsonView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void dataChanged(HttpPanelViewModelEvent e) {
    String body = ((AbstractStringHttpPanelViewModel) e.getSource()).getData();
    try {
        JSON json = toJson(body);
        if (json instanceof JSONNull) {
            // avoid the string "null" for empty bodies
            httpPanelJsonArea.setText("");
        } else {
            httpPanelJsonArea.setText(json.toString(2));
        }
    } catch (JSONException ex) {
        httpPanelJsonArea.setText(body);
    }
    if (!isEditable()) {
        httpPanelJsonArea.discardAllEdits();
    }
    // TODO: scrolling to top when new message is opened
    // httpPanelJsonArea.setCaretPosition(0);
}
 
Example #5
Source Project: zap-extensions   Author: zaproxy   File: HiddenFilesScanRule.java    License: Apache License 2.0 6 votes vote down vote up
private static List<String> getOptionalList(JSONObject jsonObj, String key) {
    if (!jsonObj.has(key)) {
        return Collections.emptyList();
    }
    JSONArray jsonArray;
    try {
        jsonArray = jsonObj.getJSONArray(key);
    } catch (JSONException jEx) {
        LOG.warn("Unable to parse JSON (" + key + ").", jEx);
        return Collections.emptyList();
    }
    List<String> newList = new ArrayList<>();
    for (int x = 0; x < jsonArray.size(); x++) {
        newList.add(jsonArray.getString(x));
    }
    return newList;
}
 
Example #6
Source Project: logsniffer   Author: mbok   File: DailyRollingLogAccess.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@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);
	}
}
 
Example #7
Source Project: geowave   Author: locationtech   File: TieredSFCIndexStrategy.java    License: Apache License 2.0 6 votes vote down vote up
/** Convert Tiered Index Metadata statistics to a JSON object */
@Override
public JSONObject toJSONObject() throws JSONException {
  final JSONObject jo = new JSONObject();
  jo.put("type", "TieredSFCIndexStrategy");

  jo.put("TierCountsSize", tierCounts.length);

  if (null == orderedTierIdToSfcIndex) {
    jo.put("orderedTierIdToSfcIndex", "null");
  } else {
    jo.put("orderedTierIdToSfcIndexSize", orderedTierIdToSfcIndex.size());
  }

  return jo;
}
 
Example #8
Source Project: cloudbreak   Author: hortonworks   File: ModelConverterUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap<>();

    Iterator<String> keysItr = object.keys();
    while (keysItr.hasNext()) {
        Object 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);
        }
        if (key.toString().contains(SEGMENT_CHARACTER)) {
            String[] split = key.toString().split(ESCAPED_SEGMENT_CHARACTER);
            value = toMap(replaceFirstSegmentOfKey(key.toString()), value);
            Map<String, Object> result = new HashMap<>();
            result.put(split[0], value);
            map = deepMerge(map, result);
        } else {
            map.put(key.toString(), value);
        }
    }
    return map;
}
 
Example #9
Source Project: cloudbreak   Author: hortonworks   File: ModelConverterUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static Map<String, Object> toMap(String key, Object value) throws JSONException {
    Map<String, Object> map = new HashMap<>();
    String[] split = key.split(ESCAPED_SEGMENT_CHARACTER);
    if (split.length == 1) {
        map.put(split[0], value);
    } else {
        Map<String, Object> stringObjectMap = toMap(replaceFirstSegmentOfKey(key), value);
        if (map.keySet().contains(split[0]) && map.get(split[0]) instanceof Map) {
            Map<String, Object> stringObjectMap1 = deepMerge((Map<String, Object>) map.get(split[0]), stringObjectMap);
            map.put(split[0], stringObjectMap1);
        } else {
            map.put(split[0], stringObjectMap);
        }
    }
    return map;
}
 
Example #10
Source Project: studio   Author: craftercms   File: WorkflowServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected DmDependencyTO getSubmittedItem_new(String site, String itemPath, SimpleDateFormat format,
                                              String globalSchDate) throws JSONException {
    DmDependencyTO submittedItem = new DmDependencyTO();
    submittedItem.setUri(itemPath);
    // TODO: check scheduled date to make sure it is not null when isNow =
    // true and also it is not past
    ZonedDateTime scheduledDate = null;
    if (globalSchDate != null && !StringUtils.isEmpty(globalSchDate)) {
        scheduledDate = getScheduledDate(site, format, globalSchDate);
    } else {
        if (submittedItem.getScheduledDate() != null) {
            scheduledDate = getScheduledDate(site, format,
                    submittedItem.getScheduledDate().format(DateTimeFormatter.ofPattern(format.toPattern())));
        }
    }
    if (scheduledDate == null) {
        submittedItem.setNow(true);
    }
    submittedItem.setScheduledDate(scheduledDate);

    return submittedItem;
}
 
Example #11
Source Project: studio   Author: craftercms   File: WorkflowServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected DmDependencyTO getSubmittedItemApproveWithoutDependencies(String site, String itemPath,
                                                                    SimpleDateFormat format, String globalSchDate)
        throws JSONException {
    DmDependencyTO submittedItem = new DmDependencyTO();
    submittedItem.setUri(itemPath);
    // TODO: check scheduled date to make sure it is not null when isNow =
    // true and also it is not past
    ZonedDateTime scheduledDate = null;
    if (globalSchDate != null && !StringUtils.isEmpty(globalSchDate)) {
        scheduledDate = getScheduledDate(site, format, globalSchDate);
    } else {
        if (submittedItem.getScheduledDate() != null) {
            scheduledDate = getScheduledDate(site, format,
                    submittedItem.getScheduledDate().format(DateTimeFormatter.ofPattern(format.toPattern())));
        }
    }
    if (scheduledDate == null) {
        submittedItem.setNow(true);
    }
    submittedItem.setScheduledDate(scheduledDate);

    return submittedItem;
}
 
Example #12
Source Project: studio   Author: craftercms   File: WorkflowServiceImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * get submitted items from JSON request
 *
 * @param site
 * @param items
 * @param format
 * @return submitted items
 * @throws JSONException
 */
protected List<DmDependencyTO> getSubmittedItems(String site, JSONArray items, SimpleDateFormat format,
                                                 String schDate) throws JSONException, ServiceLayerException {
    if (items != null) {
        int length = items.size();
        if (length > 0) {
            List<DmDependencyTO> submittedItems = new ArrayList<>();
            for (int index = 0; index < length; index++) {
                JSONObject item = items.getJSONObject(index);
                DmDependencyTO submittedItem = getSubmittedItem(site, item, format, schDate);
                submittedItems.add(submittedItem);
            }
            return submittedItems;
        }
    }
    return null;
}
 
Example #13
Source Project: Criteria2Query   Author: OHDSI   File: ConceptMapping.java    License: Apache License 2.0 5 votes vote down vote up
public static JSONObject formatOneitem(Integer conceptId){
	JSONObject jo=new JSONObject();
	try {
		jo.put("conceptId", conceptId);
		jo.put("isExcluded", 0);
		jo.put("includeDescendants", 1);//
		jo.put("includeMapped", 0);//
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return jo;
}
 
Example #14
Source Project: Criteria2Query   Author: OHDSI   File: OHDSIApis.java    License: Apache License 2.0 5 votes vote down vote up
public static JSONObject formatOneitem(Integer conceptId){
	JSONObject jo=new JSONObject();
	try {
		jo.put("conceptId", conceptId);
		jo.put("isExcluded", 0);
		jo.put("includeDescendants", 1);//
		jo.put("includeMapped", 0);//
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return jo;
}
 
Example #15
Source Project: marathon-plugin   Author: jenkinsci   File: DcosAuthImpl.java    License: Apache License 2.0 5 votes vote down vote up
private JSONObject constructJsonFromCredentials() throws AuthenticationException {
    final Secret secret = credentials.getSecret();
    try {
        return JSONObject.fromObject(Secret.toString(secret));
    } catch (JSONException e) {
        // do not spit out the contents of the json...
        final String errorMessage = "Invalid JSON in credentials '" + credentials.getId() + "'";
        LOGGER.warning(errorMessage);
        throw new AuthenticationException(errorMessage);
    }
}
 
Example #16
Source Project: pipeline-utility-steps-plugin   Author: jenkinsci   File: ReadJSONStepExecution.java    License: MIT License 5 votes vote down vote up
private boolean isNull(Object value) {
    if (value instanceof JSONNull) {
        return true;
    }
    if (value instanceof JSONObject) {
        try {
            ((Map) value).get((Object) "somekey");
        } catch (JSONException e) {
            // JSONException is returned by verifyIsNull method in JSONObject when accessing one of its properties
            return true;
        }
    }
    return false;
}
 
Example #17
Source Project: zap-extensions   Author: zaproxy   File: HttpPanelJsonView.java    License: Apache License 2.0 5 votes vote down vote up
private static JSON toJson(String s) throws JSONException {
    JSON object;
    s = s.trim();

    if (s.isEmpty()) {
        object = JSONNull.getInstance();
    } else if (s.startsWith("{")) {
        object = JSONObject.fromObject(s);
    } else if (s.startsWith("[")) {
        object = JSONArray.fromObject(s);
    } else {
        throw new JSONException("Expected a '{', '[', or an empty message");
    }
    return object;
}
 
Example #18
Source Project: zap-extensions   Author: zaproxy   File: HiddenFilesScanRule.java    License: Apache License 2.0 5 votes vote down vote up
private static String getOptionalString(JSONObject jsonObj, String key) {
    if (!jsonObj.has(key)) {
        return "";
    }
    try {
        return jsonObj.getString(key);
    } catch (JSONException jEx) {
        LOG.warn("Unable to parse JSON (" + key + ").", jEx);
        return "";
    }
}
 
Example #19
Source Project: kubernetes-plugin   Author: jenkinsci   File: KubernetesFolderProperty.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public AbstractFolderProperty<?> reconfigure(StaplerRequest req, JSONObject form) throws FormException {
    if (form == null) {
        return null;
    }

    // ignore modifications silently and return the unmodified object if the user
    // does not have the ADMINISTER Permission
    if (!userHasAdministerPermission()) {
        return this;
    }

    try {
        Set<String> inheritedGrants = new HashSet<>();
        collectAllowedClouds(inheritedGrants, getOwner().getParent());

        Set<String> permittedClouds = new HashSet<>();
        JSONArray names = form.names();
        if (names != null) {
            for (Object name : names) {
                String strName = (String) name;

                if (strName.startsWith(PREFIX_USAGE_PERMISSION) && form.getBoolean(strName)) {
                    String cloud = StringUtils.replaceOnce(strName, PREFIX_USAGE_PERMISSION, "");

                    if (isUsageRestrictedKubernetesCloud(Jenkins.get().getCloud(cloud))
                            && !inheritedGrants.contains(cloud)) {
                        permittedClouds.add(cloud);
                    }
                }
            }
        }
        this.permittedClouds.clear();
        this.permittedClouds.addAll(permittedClouds);
    } catch (JSONException e) {
        LOGGER.log(Level.SEVERE, e, () -> "reconfigure failed: " + e.getMessage());
    }
    return this;
}
 
Example #20
Source Project: gerrit-events   Author: sonyxperiadev   File: GerritJsonEventFactory.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the value of a JSON property as a boolean if it exists and boolean value
 * 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 or not boolean value.
 * @return the value for the key as a boolean.
 */
public static boolean getBoolean(JSONObject json, String key, boolean defaultValue) {
    if (json.containsKey(key)) {
        boolean result;
        try {
            result = json.getBoolean(key);
        } catch (JSONException ex) {
            result = defaultValue;
        }
        return result;
    } else {
        return defaultValue;
    }
}
 
Example #21
Source Project: geowave   Author: locationtech   File: XZHierarchicalIndexStrategy.java    License: Apache License 2.0 5 votes vote down vote up
/** Convert XZHierarchical Index Metadata statistics to a JSON object */
@Override
public JSONObject toJSONObject() throws JSONException {
  final 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;
}
 
Example #22
Source Project: geowave   Author: locationtech   File: CompoundIndexStrategy.java    License: Apache License 2.0 5 votes vote down vote up
/** Convert Tiered Index Metadata statistics to a JSON object */
@Override
public JSONObject toJSONObject() throws JSONException {
  final JSONObject jo = new JSONObject();
  jo.put("type", "CompoundIndexMetaDataWrapper");
  jo.put("index", index);
  return jo;
}
 
Example #23
Source Project: geowave   Author: locationtech   File: AbstractDataStatistics.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JSONObject toJSONObject(final InternalAdapterStore store) throws JSONException {
  final JSONObject jo = new JSONObject();
  jo.put("dataType", store.getTypeName(adapterId));
  jo.put("statsType", statisticsType.getString());
  if ((extendedId != null) && !extendedId.isEmpty()) {
    jo.put("extendedId", extendedId);
  }
  jo.put(resultsName(), resultsValue());
  return jo;
}
 
Example #24
Source Project: cloudbreak   Author: hortonworks   File: ModelConverterUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static Map<String, Object> jsonToMap(Object json) throws JSONException {
    Map<String, Object> retMap = new HashMap<>();
    if (json != null) {
        retMap = toMap(JSONObject.fromObject(json));
    }
    return retMap;
}
 
Example #25
Source Project: cloudbreak   Author: hortonworks   File: ModelConverterUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static List<Object> toList(JSONArray array) throws JSONException {
    List<Object> list = new ArrayList<>();
    for (int i = 0; i < array.size(); i++) {
        Object value = array.get(i);
        if (value instanceof JSONArray) {
            value = toList((JSONArray) value);
        } else if (value instanceof JSONObject) {
            value = toMap((JSONObject) value);
        }
        list.add(value);
    }
    return list;
}
 
Example #26
Source Project: jmeter-plugins   Author: undera   File: JSONFormatter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process() {
    JMeterContext context = getThreadContext();
    String responseData = context.getPreviousResult().getResponseDataAsString();
    try {
        String str = this.formatJSON(responseData);
        context.getPreviousResult().setResponseData(str.getBytes());
    } catch (JSONException e) {
        log.warn("Failed to format JSON: " + e.getMessage());
        log.debug("Failed to format JSON", e);
    }
}
 
Example #27
Source Project: Leo   Author: QihooTest   File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 单层解析json字符串
 * @param str
 * @return Map<String, Object> 异常返回null
 */
@SuppressWarnings("unchecked")
public static Map<String, Object> getResult(String str) {
	JsonUtil jsonUtil = new JsonUtil();
	try {
		jsonUtil.oneResult = JSONObject.fromObject(str);
	} catch (JSONException e) {
		jsonUtil.oneResult = null;
	}
	return jsonUtil.oneResult;
}
 
Example #28
Source Project: Leo   Author: QihooTest   File: StringUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 把map表转换为json格式字符串,转换失败返回null
 * @param map
 * @return String
 */
public static String getJsonStrFromMap(Map<String, String> map) {
	JSONObject oneResult = new JSONObject();
	try {
		oneResult = JSONObject.fromObject(map);
	} catch (JSONException e) {
		log.error("从map表:" + map.toString() + "转换为json字符串出错");
		log.error(e.getMessage());
		return null;
	}
	return oneResult.toString();
}
 
Example #29
Source Project: openemm   Author: agnitas-org   File: ComProfileFieldDaoImpl.java    License: GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public ComProfileField mapRow(ResultSet resultSet, int row) throws SQLException {
	ComProfileField readProfileField = new ComProfileFieldImpl();

	readProfileField.setCompanyID(resultSet.getInt(FIELD_COMPANY_ID));
	readProfileField.setShortname(resultSet.getString(FIELD_SHORTNAME));
	readProfileField.setDescription(resultSet.getString(FIELD_DESCRIPTION));
	readProfileField.setColumn(resultSet.getString(FIELD_COLUMN_NAME));
	readProfileField.setDefaultValue(resultSet.getString(FIELD_DEFAULT_VALUE));
	readProfileField.setModeEdit(resultSet.getInt(FIELD_MODE_EDIT));
	readProfileField.setModeInsert(resultSet.getInt(FIELD_MODE_INSERT));
	readProfileField.setCreationDate(resultSet.getTimestamp(FIELD_CREATION_DATE));
	readProfileField.setChangeDate(resultSet.getTimestamp(FIELD_CHANGE_DATE));
	readProfileField.setHistorize(resultSet.getBoolean(FIELD_HISTORIZE));

	Object sortObject = resultSet.getObject(FIELD_SORT);
	if (sortObject != null) {
		readProfileField.setSort(((Number)sortObject).intValue());
	} else {
		readProfileField.setSort(MAX_SORT_INDEX);
	}

	Object lineObject = resultSet.getObject(FIELD_LINE);
	if (lineObject != null) {
		readProfileField.setLine(((Number)lineObject).intValue());
	} else {
		readProfileField.setLine(0);
	}

	Object interestObject = resultSet.getObject(FIELD_ISINTEREST);
	if (interestObject != null) {
		readProfileField.setInterest(((Number)interestObject).intValue());
	} else {
		readProfileField.setInterest(0);
	}

	String allowedValuesJson = resultSet.getString(FIELD_ALLOWED_VALUES);
	String[] allowedValues = null;
	if (allowedValuesJson != null) {
		try {
			JSONArray array = JSONArray.fromObject(allowedValuesJson);
			allowedValues = new String[array.size()];
			for (int i = 0; i < array.size(); i++) {
				allowedValues[i] = array.getString(i);
			}
		} catch (JSONException e) {
			logger.error("Error occurred while parsing JSON: " + e.getMessage(), e);
		}
	}
	readProfileField.setAllowedValues(allowedValues);

	return readProfileField;
}
 
Example #30
Source Project: zap-extensions   Author: zaproxy   File: MongoDbInjection.java    License: Apache License 2.0 4 votes vote down vote up
private static String getParamJsonString(String param, String[] params) throws JSONException {
    JSONObject internal = new JSONObject(), external = new JSONObject();
    internal.put(params[0], params[1]);
    external.put(param, internal);
    return external.toString();
}