Java Code Examples for net.sf.json.JSONObject#getBoolean()

The following examples show how to use net.sf.json.JSONObject#getBoolean() . 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: JiraConverter.java    From benten with MIT License 8 votes vote down vote up
public static List<JSONObject> getRequiredFields(JSONObject fields){
    List<JSONObject> requiredFields = new ArrayList<>();

    Iterator<?> iterator = fields.keys();
    while (iterator.hasNext()) {
        String key = (String)iterator.next();
        JSONObject jsonChildObject = fields.getJSONObject(key);

        boolean required = jsonChildObject.getBoolean("required");
        if(required) {
            if(!key.startsWith("customfield")) {
                if ("Project".equals(jsonChildObject.getString("name")) || "Issue Type".equals(jsonChildObject.getString("name"))
                        || "Summary".equals(jsonChildObject.getString("name")))
                    continue;
            }
            jsonChildObject.put("key", key);
            requiredFields.add(jsonChildObject);

        }

    }
    return requiredFields;
}
 
Example 2
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 3
Source File: TemplateImplementationProperty.java    From ez-templates with Apache License 2.0 6 votes vote down vote up
@Override
public JobProperty<?> newInstance(StaplerRequest request, JSONObject formData) throws FormException {
    if (formData.size() > 0 && formData.has("useTemplate")) {
        JSONObject useTemplate = formData.getJSONObject("useTemplate");

        String templateJobName = useTemplate.getString("templateJobName");
        boolean syncMatrixAxis = useTemplate.getBoolean("syncMatrixAxis");
        boolean syncDescription = useTemplate.getBoolean("syncDescription");
        boolean syncBuildTriggers = useTemplate.getBoolean("syncBuildTriggers");
        boolean syncDisabled = useTemplate.getBoolean("syncDisabled");
        boolean syncSecurity = useTemplate.getBoolean("syncSecurity");
        boolean syncScm = useTemplate.getBoolean("syncScm");
        boolean syncOwnership = useTemplate.getBoolean("syncOwnership");
        boolean syncAssignedLabel = useTemplate.getBoolean("syncAssignedLabel");

        return new TemplateImplementationProperty(templateJobName, syncMatrixAxis, syncDescription, syncBuildTriggers, syncDisabled, syncSecurity, syncScm, syncOwnership, syncAssignedLabel);
    }

    return null;
}
 
Example 4
Source File: AquaMicroScannerBuilder.java    From aqua-microscanner-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
	// To persist global configuration information,
	// set that to properties and call save().
	microScannerToken = Secret.fromString(formData.getString("microScannerToken"));
	caCertificates = formData.getBoolean("caCertificates");
	save();
	return super.configure(req, formData);
}
 
Example 5
Source File: RepairnatorPostBuild.java    From repairnator with MIT License 5 votes vote down vote up
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
    req.bindJSON(this, formData);
    this.useNPEFix = formData.getBoolean("useNPEFix");
    this.useAstorJKali = formData.getBoolean("useAstorJKali");
    this.useAstorJMut = formData.getBoolean("useAstorJMut");
    this.useNPEFixSafe = formData.getBoolean("useNPEFixSafe");
    this.useNopolTestExclusionStrategy = formData.getBoolean("useNopolTestExclusionStrategy");
    this.useSorald = formData.getBoolean("useSorald");

    save();
    return true;
}
 
Example 6
Source File: RecordPermissionsRest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Updates the policy policy file with the corresponding 'update' permissions from the record policy.
 *
 * @param json The json from record policy update
 * @param policyType The PolicyType from the policy policy
 * @return The update XACML policy
 */
private XACMLPolicy updatePolicyPolicy(String json, PolicyType policyType) {
    AttributeDesignatorType subjectIdAttrDesig = createSubjectIdAttrDesig();
    AttributeDesignatorType groupAttrDesig = createGroupAttrDesig();

    JSONObject jsonObject = JSONObject.fromObject(json);
    JSONObject updateObj = jsonObject.optJSONObject("urn:update");
    if (updateObj == null) {
        throw new IllegalArgumentException("Invalid JSON representation of a Policy. Missing update rule.");
    }

    AnyOfType readUserAnyOf = policyType.getRule().get(0).getTarget().getAnyOf().get(1);
    AnyOfType updateUserAnyOf = policyType.getRule().get(1).getTarget().getAnyOf().get(1);
    readUserAnyOf.getAllOf().clear();
    updateUserAnyOf.getAllOf().clear();
    if (updateObj.opt("everyone") == null) {
        throw new IllegalArgumentException("Invalid JSON representation of a Policy. Missing everyone field.");
    }
    if (updateObj.getBoolean("everyone")) {
        MatchType userRoleMatch = createUserRoleMatch();
        AllOfType everyoneAllOf = new AllOfType();
        everyoneAllOf.getMatch().add(userRoleMatch);
        readUserAnyOf.getAllOf().add(everyoneAllOf);
        updateUserAnyOf.getAllOf().add(everyoneAllOf);
    } else {
        JSONArray usersArray = updateObj.optJSONArray("users");
        JSONArray groupsArray = updateObj.optJSONArray("groups");
        if (usersArray == null || groupsArray == null) {
            throw new IllegalArgumentException("Invalid JSON representation of a Policy."
                    + " Users or groups not set properly for update rule");
        }
        addUsersOrGroupsToAnyOf(usersArray, subjectIdAttrDesig, readUserAnyOf, updateUserAnyOf);
        addUsersOrGroupsToAnyOf(groupsArray, groupAttrDesig, readUserAnyOf, updateUserAnyOf);
    }

    return policyManager.createPolicy(policyType);
}
 
Example 7
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 8
Source File: DatadogHttpClient.java    From jenkins-datadog-plugin with MIT License 5 votes vote down vote up
@Override
public boolean validate() throws IOException, ServletException {
    String urlParameters = "?api_key=" + apiKey;
    HttpURLConnection conn = null;
    boolean status = true;
    try {
        // Make request
        conn = getHttpURLConnection(new URL(url + VALIDATE + urlParameters));
        conn.setRequestMethod("GET");

        // Get response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        rd.close();

        // Validate
        JSONObject json = (JSONObject) JSONSerializer.toJSON(result.toString());
        if (!json.getBoolean("valid")) {
            status = false;
        }
    } catch (Exception e) {
        if (conn != null && conn.getResponseCode() == HTTP_FORBIDDEN) {
            logger.severe("Hmmm, your API key may be invalid. We received a 403 error.");
        } else {
            logger.severe(String.format("Client error: %s", e.toString()));
        }
        status = false;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return status;
}
 
Example 9
Source File: DeflakeAction.java    From flaky-test-handler-plugin with Apache License 2.0 5 votes vote down vote up
private static ParameterValue getBooleanParam(JSONObject formData, String paramName) {
  JSONObject paramObj = JSONObject.fromObject(formData.get(paramName));
  String name = paramObj.getString("name");
  FlakyTestResultAction.logger.log(Level.FINE,
      "Param: " + name + " with value: " + paramObj.getBoolean("value"));
  return new BooleanParameterValue(name, paramObj.getBoolean("value"));
}
 
Example 10
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 11
Source File: RecordPermissionsRest.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Converts a record policy abridged JSON into a XACML policy object.
 *
 * @param json The record policy JSON
 * @param policyType the PolicyType from the record policy
 * @return The updated XACMLPolicy object
 */
private XACMLPolicy recordJsonToPolicy(String json, PolicyType policyType) {
    String masterBranch = policyType.getRule().get(4).getTarget().getAnyOf().get(0).getAllOf().get(0).getMatch()
            .get(1).getAttributeValue().getContent().get(0).toString();
    policyType.getRule().clear();

    AttributeDesignatorType actionIdAttrDesig = createActionIdAttrDesig();
    AttributeDesignatorType subjectIdAttrDesig = createSubjectIdAttrDesig();
    AttributeDesignatorType groupAttrDesig = createGroupAttrDesig();
    AttributeDesignatorType branchAttrDesig = createBranchAttrDesig();
    AttributeValueType branchAttrVal = createAttributeValue(XSD.STRING, masterBranch);

    JSONObject jsonObject = JSONObject.fromObject(json);
    Iterator<?> keys = jsonObject.keys();

    while (keys.hasNext()) {
        String key = (String)keys.next();
        TargetType target = new TargetType();
        RuleType rule = createRule(EffectType.PERMIT, key, target);
        AttributeValueType ruleTypeAttrVal = new AttributeValueType();
        ruleTypeAttrVal.setDataType(XSD.STRING);

        // Setup Rule Type
        MatchType ruleTypeMatch = createMatch(XACML.STRING_EQUALS, actionIdAttrDesig, ruleTypeAttrVal);
        ruleTypeAttrVal.getContent().clear();
        switch (key) {
            case "urn:read":
                ruleTypeAttrVal.getContent().add(Read.TYPE);
                break;
            case "urn:delete":
                ruleTypeAttrVal.getContent().add(Delete.TYPE);
                break;
            case "urn:update":
                ruleTypeAttrVal.getContent().add(Update.TYPE);
                break;
            case "urn:modify":
                ruleTypeAttrVal.getContent().add("http://mobi.com/ontologies/catalog#Modify");
                break;
            case "urn:modifyMaster":
                ruleTypeAttrVal.getContent().add("http://mobi.com/ontologies/catalog#Modify");
                break;
            default:
                throw new MobiException("Invalid rule key: " + key);
        }

        AnyOfType anyOfType = new AnyOfType();
        AllOfType allOfType = new AllOfType();
        anyOfType.getAllOf().add(allOfType);
        allOfType.getMatch().add(ruleTypeMatch);

        if (key.equalsIgnoreCase("urn:modifyMaster")) {
            MatchType branchMatch = createMatch(XACML.STRING_EQUALS, branchAttrDesig, branchAttrVal);
            allOfType.getMatch().add(branchMatch);
        }
        rule.getTarget().getAnyOf().add(anyOfType);

        // Setup Users
        AnyOfType usersGroups = new AnyOfType();
        JSONObject jsonRule = jsonObject.optJSONObject(key);
        if (jsonRule == null) {
            throw new IllegalArgumentException("Invalid JSON representation of a Policy. Missing rule " + key);
        }
        if (jsonRule.opt("everyone") == null) {
            throw new IllegalArgumentException("Invalid JSON representation of a Policy. Missing everyone field"
                    + "for " + key);
        }
        if (jsonRule.getBoolean("everyone")) {
            MatchType userRoleMatch = createUserRoleMatch();
            AllOfType everyoneAllOf = new AllOfType();
            everyoneAllOf.getMatch().add(userRoleMatch);
            usersGroups.getAllOf().add(everyoneAllOf);
        } else {
            JSONArray usersArray = jsonRule.optJSONArray("users");
            JSONArray groupsArray = jsonRule.optJSONArray("groups");
            if (usersArray == null || groupsArray == null) {
                throw new IllegalArgumentException("Invalid JSON representation of a Policy."
                        + " Users or groups not set properly for " + key);
            }
            addUsersOrGroupsToAnyOf(usersArray, subjectIdAttrDesig, usersGroups);
            addUsersOrGroupsToAnyOf(groupsArray, groupAttrDesig, usersGroups);
        }
        rule.getTarget().getAnyOf().add(usersGroups);

        if (key.equalsIgnoreCase("urn:modify")) {
            ConditionType condition = new ConditionType();
            condition.setExpression(createMasterBranchExpression(masterBranch));
            rule.setCondition(condition);
        }
        policyType.getRule().add(rule);
    }

    return policyManager.createPolicy(policyType);
}
 
Example 12
Source File: WorkflowServiceImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
protected ResultTO submitForApproval(final String site, String submittedBy, final String request,
                                     final boolean delete) throws ServiceLayerException {
    RequestContext requestContext = RequestContextBuilder.buildSubmitContext(site, submittedBy);
    ResultTO result = new ResultTO();
    try {
        SimpleDateFormat format = new SimpleDateFormat(StudioConstants.DATE_PATTERN_WORKFLOW_WITH_TZ);
        JSONObject requestObject = JSONObject.fromObject(request);
        JSONArray items = requestObject.getJSONArray(JSON_KEY_ITEMS);
        int length = items.size();
        if (length > 0) {
            for (int index = 0; index < length; index++) {
                objectStateService.setSystemProcessing(site, items.optString(index), true);
            }
        }
        boolean isNow = (requestObject.containsKey(JSON_KEY_SCHEDULE)) ?
                StringUtils.equalsIgnoreCase(requestObject.getString(JSON_KEY_SCHEDULE), JSON_KEY_IS_NOW) : false;
        ZonedDateTime scheduledDate = null;
        if (!isNow) {
            scheduledDate = (requestObject.containsKey(JSON_KEY_SCHEDULED_DATE)) ?
                    getScheduledDate(site, format, requestObject.getString(JSON_KEY_SCHEDULED_DATE)) : null;
        }
        boolean sendEmail = (requestObject.containsKey(JSON_KEY_SEND_EMAIL)) ?
                requestObject.getBoolean(JSON_KEY_SEND_EMAIL) : false;

        String environment = (requestObject != null && requestObject.containsKey(JSON_KEY_ENVIRONMENT))
                ? requestObject.getString(JSON_KEY_ENVIRONMENT) : null;

        String submissionComment = (requestObject != null && requestObject.containsKey(JSON_KEY_SUBMISSION_COMMENT))
                ? requestObject.getString(JSON_KEY_SUBMISSION_COMMENT) : null;
        // TODO: check scheduled date to make sure it is not null when isNow
        // = true and also it is not past


        String schDate = null;
        if (requestObject.containsKey(JSON_KEY_SCHEDULED_DATE)) {
            schDate = requestObject.getString(JSON_KEY_SCHEDULED_DATE);
        }
        if (length > 0) {
            List<DmDependencyTO> submittedItems = new ArrayList<DmDependencyTO>();
            for (int index = 0; index < length; index++) {
                String stringItem = items.optString(index);
                DmDependencyTO submittedItem = getSubmittedItem(site, stringItem, format, schDate,null);
                String user = submittedBy;
                submittedItems.add(submittedItem);
                if (delete) {
                    submittedItem.setSubmittedForDeletion(true);
                }
            }
            submittedItems.addAll(addDependenciesForSubmitForApproval(site, submittedItems, format, schDate));
            List<String> submittedPaths = new ArrayList<String>();
            for (DmDependencyTO goLiveItem : submittedItems) {
                submittedPaths.add(goLiveItem.getUri());
                objectStateService.setSystemProcessing(site, goLiveItem.getUri(), true);
                DependencyRules rule = new DependencyRules(site);
                rule.setObjectStateService(objectStateService);
                rule.setContentService(contentService);
                Set<DmDependencyTO> depSet = rule.applySubmitRule(goLiveItem);
                for (DmDependencyTO dep : depSet) {
                    submittedPaths.add(dep.getUri());
                    objectStateService.setSystemProcessing(site, dep.getUri(), true);
                }
            }
            List<DmError> errors = submitToGoLive(submittedItems, scheduledDate, sendEmail, delete, requestContext,
                    submissionComment, environment);
            SiteFeed siteFeed = siteService.getSite(site);
            AuditLog auditLog = auditServiceInternal.createAuditLogEntry();
            auditLog.setOperation(OPERATION_REQUEST_PUBLISH);
            auditLog.setActorId(submittedBy);
            auditLog.setSiteId(siteFeed.getId());
            auditLog.setPrimaryTargetId(site);
            auditLog.setPrimaryTargetType(TARGET_TYPE_CONTENT_ITEM);
            auditLog.setPrimaryTargetValue(site);
            auditServiceInternal.insertAuditLog(auditLog);
            result.setSuccess(true);
            result.setStatus(200);
            result.setMessage(notificationService.getNotificationMessage(site, NotificationMessageType
                        .CompleteMessages,COMPLETE_SUBMIT_TO_GO_LIVE_MSG,Locale.ENGLISH));
            for (String relativePath : submittedPaths) {
                objectStateService.setSystemProcessing(site, relativePath, false);
            }
        }
    } catch (Exception e) {
        result.setSuccess(false);
        result.setMessage(e.getMessage());
        logger.error("Error while submitting content for approval.", e);
    }
    return result;

}
 
Example 13
Source File: JobUiProperty.java    From DotCi with MIT License 4 votes vote down vote up
@Override
public JobUiProperty newInstance(final StaplerRequest req, final JSONObject formData) throws FormException {
    return new JobUiProperty(formData.getBoolean("newUi"));
}
 
Example 14
Source File: BuildTagsProperty.java    From DotCi with MIT License 4 votes vote down vote up
@Override
public BuildTagsProperty newInstance(final StaplerRequest req, final JSONObject formData) throws FormException {
    return new BuildTagsProperty(formData.getBoolean("shouldBuildTags"));
}
 
Example 15
Source File: PullRequestRebuildProperty.java    From DotCi with MIT License 4 votes vote down vote up
@Override
public PullRequestRebuildProperty newInstance(StaplerRequest req, JSONObject formData) throws FormException {
    return new PullRequestRebuildProperty(formData.getBoolean("buildPullRequestsFromSameRepo"));
}