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 File: BlazeMeterHttpUtils.java    From jmeter-bzm-plugins with 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 File: WorkflowServiceImpl.java    From studio with 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 #3
Source File: WorkflowServiceImpl.java    From studio with 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 #4
Source File: WorkflowServiceImpl.java    From studio with 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 #5
Source File: ModelConverterUtils.java    From cloudbreak with 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 #6
Source File: ModelConverterUtils.java    From cloudbreak with 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 #7
Source File: TieredSFCIndexStrategy.java    From geowave with 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 File: DailyRollingLogAccess.java    From logsniffer with 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 #9
Source File: HiddenFilesScanRule.java    From zap-extensions with 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 #10
Source File: HttpPanelJsonView.java    From zap-extensions with 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 #11
Source File: HttpPanelJsonView.java    From zap-extensions with 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 #12
Source File: MarathonBuilderImpl.java    From marathon-plugin with 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 #13
Source File: CompoundIndexStrategy.java    From geowave with 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 #14
Source File: ConceptMapping.java    From Criteria2Query with 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 File: OHDSIApis.java    From Criteria2Query with 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 #16
Source File: ModelConverterUtils.java    From cloudbreak with 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 #17
Source File: DcosAuthImpl.java    From marathon-plugin with 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 #18
Source File: ModelConverterUtils.java    From cloudbreak with 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 #19
Source File: JSONFormatter.java    From jmeter-plugins with 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 #20
Source File: AbstractDataStatistics.java    From geowave with 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 #21
Source File: JsonUtil.java    From Leo with 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 #22
Source File: XZHierarchicalIndexStrategy.java    From geowave with 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 #23
Source File: ReadJSONStepExecution.java    From pipeline-utility-steps-plugin with 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 #24
Source File: GerritJsonEventFactory.java    From gerrit-events with 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 #25
Source File: KubernetesFolderProperty.java    From kubernetes-plugin with 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 #26
Source File: HiddenFilesScanRule.java    From zap-extensions with 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 #27
Source File: StringUtil.java    From Leo with 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 #28
Source File: HttpPanelJsonView.java    From zap-extensions with 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 #29
Source File: MongoDbInjection.java    From zap-extensions with 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();
}
 
Example #30
Source File: WorkflowServiceImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
@ValidateParams
public ResultTO reject(@ValidateStringParam(name = "site") String site,
                       @ValidateStringParam(name = "user") String user,
                       String request) throws ServiceLayerException {
    ResultTO result = new ResultTO();
    try {
        String approver = user;
        if (StringUtils.isEmpty(approver)) {
            approver = securityService.getCurrentUser();
        }
        JSONObject requestObject = JSONObject.fromObject(request);
        String reason = (requestObject.containsKey(JSON_KEY_REASON)) ? requestObject.getString(JSON_KEY_REASON) : "";
        JSONArray items = requestObject.getJSONArray(JSON_KEY_ITEMS);
        String scheduledDate = null;
        if (requestObject.containsKey(JSON_KEY_SCHEDULED_DATE)) {
            scheduledDate = requestObject.getString(JSON_KEY_SCHEDULED_DATE);
        }
        int length = items.size();
        if (length > 0) {
            SimpleDateFormat format = new SimpleDateFormat(StudioConstants.DATE_PATTERN_WORKFLOW_WITH_TZ);
            List<DmDependencyTO> submittedItems = new ArrayList<DmDependencyTO>();
            for (int index = 0; index < length; index++) {
                String stringItem = items.optString(index);
                //JSONObject item = items.getJSONObject(index);
                DmDependencyTO submittedItem = null; //getSubmittedItem(site, item, format, scheduledDate);
                submittedItem = getSubmittedItem(site, stringItem, format, scheduledDate, null);
                submittedItems.add(submittedItem);
            }
            List<String> paths = new ArrayList<String>();
            List<AuditLogParameter> auditLogParameters = new ArrayList<AuditLogParameter>();
            for (DmDependencyTO goLiveItem : submittedItems) {
                if (contentService.contentExists(site, goLiveItem.getUri())) {
                    paths.add(goLiveItem.getUri());
                }
                AuditLogParameter auditLogParameter = new AuditLogParameter();
                auditLogParameter.setTargetId(site + ":" + goLiveItem.getUri());
                auditLogParameter.setTargetType(TARGET_TYPE_CONTENT_ITEM);
                auditLogParameter.setTargetValue(goLiveItem.getUri());
                auditLogParameters.add(auditLogParameter);
            }
            objectStateService.setSystemProcessingBulk(site, paths, true);
            Set<String> cancelPaths = new HashSet<String>();
            cancelPaths.addAll(paths);
            deploymentService.cancelWorkflowBulk(site, cancelPaths);
            reject(site, submittedItems, reason, approver);
            SiteFeed siteFeed = siteService.getSite(site);
            AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
            auditLog.setOperation(OPERATION_REJECT);
            auditLog.setActorId(approver);
            auditLog.setSiteId(siteFeed.getId());
            auditLog.setPrimaryTargetId(site);
            auditLog.setPrimaryTargetType(TARGET_TYPE_SITE);
            auditLog.setPrimaryTargetValue(site);
            auditLog.setParameters(auditLogParameters);
            auditServiceInternal.insertAuditLog(auditLog);
            objectStateService.setSystemProcessingBulk(site, paths, false);
            result.setSuccess(true);
            result.setStatus(200);
            result.setMessage(notificationService.getNotificationMessage(site, NotificationMessageType
                    .CompleteMessages, NotificationService.COMPLETE_REJECT, Locale.ENGLISH));
        } else {
            result.setSuccess(false);
            result.setMessage("No items provided for preparation.");
        }
    } catch (JSONException | DeploymentException e) {
        result.setSuccess(false);
        result.setMessage(e.getMessage());
    }
    return result;
}