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

The following examples show how to use net.sf.json.JSONObject#optString() . 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: GlobalConfigurationService.java    From sonar-quality-gates-plugin with MIT License 6 votes vote down vote up
protected void addGlobalConfigDataForSonarInstance(JSONObject globalConfigData) {

        String name = globalConfigData.optString("name");
        int timeToWait = globalConfigData.optInt("timeToWait");
		int maxWaitTime = globalConfigData.optInt("maxWaitTime");
        String url = globalConfigData.optString("url");

        if (!"".equals(name)) {

            GlobalConfigDataForSonarInstance globalConfigDataForSonarInstance;
            String token = globalConfigData.optString("token");
            if (StringUtils.isNotEmpty(token)) {
                globalConfigDataForSonarInstance = new GlobalConfigDataForSonarInstance(name, url, globalConfigData.optString("token"), timeToWait, maxWaitTime);
            } else {
                globalConfigDataForSonarInstance = new GlobalConfigDataForSonarInstance(name, url, globalConfigData.optString("account"), Secret.fromString(Util.fixEmptyAndTrim(globalConfigData.optString("password"))), timeToWait, maxWaitTime);
            }

            if (!containsGlobalConfigWithName(name)) {
                listOfGlobalConfigInstances.add(globalConfigDataForSonarInstance);
            }
        }
    }
 
Example 2
Source File: Skype.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Retrieves access token for bot
 */
protected void getAccessToken() throws Exception {
	String url = "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token";

	String type = "application/x-www-form-urlencoded";
	String data = "grant_type=client_credentials&client_id=" + appId + "&client_secret=" + appPassword + "&scope=https%3A%2F%2Fapi.botframework.com%2F.default";
	String json = Utils.httpPOST(url, type, data);
	
	JSONObject root = (JSONObject)JSONSerializer.toJSON(json);
	
	if(root.optString("token_type").equals("Bearer")) {
		int tokenExpiresIn = root.optInt("expires_in");
		String accessToken = root.optString("access_token");
		
		setToken(accessToken);
		this.tokenExpiry = new Date(System.currentTimeMillis() + (tokenExpiresIn * 1000));
		
		log("Skype access token retrieved.", Level.INFO);
	} else {
		log("Skype get access token failed:", Level.INFO);
	}
	
	saveProperties();
}
 
Example 3
Source File: AbstractGHBranchSubscriber.java    From github-integration-plugin with MIT License 6 votes vote down vote up
protected BranchInfo fromJson(JSONObject json, boolean tagsAware) {
    JSONObject jsonRepository = json.getJSONObject("repository");
    final String repo = jsonRepository.getString("full_name");

    String branchName = json.getString("ref");
    String refType = json.optString("ref_type", null);
    String fullRef = branchName;

    boolean tag = false;

    if (branchName.startsWith("refs/heads/")) {
        branchName = branchName.replace("refs/heads/", "");
    }

    if ("tag".equals(refType)) {
        tag = true;
    } else if (branchName.startsWith("refs/tags/")) {
        // backwards compatibility
        if (tagsAware) {
            branchName = branchName.replace("refs/tags/", "");
        }
        tag = true;
    }

    return new BranchInfo(repo, branchName, fullRef, tag);
}
 
Example 4
Source File: PolicyRestTest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void getPoliciesTest() {
    Response response = target().path("policies").request().get();
    assertEquals(response.getStatus(), 200);
    verify(policyManager).getPolicies(any(PolicyQueryParams.class));
    try {
        JSONArray result = JSONArray.fromObject(response.readEntity(String.class));
        assertEquals(result.size(), 1);
        JSONObject policyObj = result.optJSONObject(0);
        assertNotNull(policyObj);
        String id = policyObj.optString("PolicyId");
        assertNotNull(id);
        assertEquals(id, policyId.stringValue());
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 5
Source File: ProvRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private List<String> getResources(JSONArray array) {
    List<String> resources = new ArrayList<>();
    for (int i = 0; i < array.size(); i++) {
        JSONObject obj = array.optJSONObject(i);
        assertNotNull(obj);
        String iri = obj.optString("@id");
        assertNotNull(iri);
        resources.add(iri);
    }
    return resources;
}
 
Example 6
Source File: PackerInstallation.java    From packer-plugin with MIT License 5 votes vote down vote up
@DataBoundConstructor
public PackerInstallation(String name, String home, String params,
                          JSONObject templateMode,
                          List<PackerFileEntry> fileEntries,
                          List<? extends ToolProperty<?>> properties) {
    this(name, launderHome(home), params,
         templateMode.optString("jsonTemplate", null),
         templateMode.optString("jsonTemplateText", null),
         Strings.isNullOrEmpty(templateMode.optString("value", null)) ? TemplateMode.TEXT.toMode() : templateMode.getString("value"),
         fileEntries, properties);
}
 
Example 7
Source File: WeChat.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Retrieves access token for bot.
 * Access token must be obtained before calling APIs
 */
protected void getAccessToken() throws Exception {
	String url = "https://";
	url = url.concat( this.international ? INTERNATIONAL_API : CHINA_API );
	url = url.concat("/cgi-bin/token");
	
	String data = "?grant_type=client_credential&appid=" + appId + "&secret=" + appPassword;
	url = url.concat(data);
	
	String json = Utils.httpGET(url);
	
	JSONObject root = (JSONObject)JSONSerializer.toJSON(json);
	
	if(root.optString("access_token") != null) {
		int tokenExpiresIn = root.optInt("expires_in");
		String accessToken = root.optString("access_token");
		
		setToken(accessToken);
		this.tokenExpiry = new Date(System.currentTimeMillis() + (tokenExpiresIn * 1000));
		
		log("WeChat access token retrieved - token: " + accessToken + ", expires in " + tokenExpiresIn, Level.INFO);
	} else if (root.optString("errmsg") != null) {
		String errMsg = root.optString("errmsg");
		int errCode = root.optInt("errcode");
		log("WeChat get access token failed - Error code:" + errCode + ", Error Msg: " + errMsg, Level.INFO);
	} else {
		log("WeChat get access token failed.", Level.INFO);
	}
	
	saveProperties();
}
 
Example 8
Source File: SkypeActivity.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public SkypeActivity(String json) {
	JSONObject root = (JSONObject)JSONSerializer.toJSON(json);
	
	this.type = root.optString("type");
	this.id = root.optString("id");
	this.timestamp = root.optString("timestamp");
	this.serviceURL = root.optString("serviceUrl");
	this.channelId = root.optString("channelId");
	
	JSONObject from = root.optJSONObject("from");
	if(from != null) {
		this.fromId = from.optString("id");
		this.fromName = from.optString("name");
	}
	
	JSONObject conversation = root.optJSONObject("conversation");
	if(conversation != null) {
		this.conversationId = conversation.optString("id");
		this.conversationName = conversation.optString("name");
	}
	
	JSONObject recipient = root.optJSONObject("recipient");
	if(recipient != null) {
		this.recipientId = recipient.optString("id");
		this.recipientName = recipient.optString("name");
	}
	
	this.text = root.optString("text");
}
 
Example 9
Source File: WebSocketAPI.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private void optionalResponse(WebSocketProxy proxy, JSON response, JSONObject request)
        throws IOException {
    if (request != null) {
        String id = request.optString("id", "");
        if (id.length() > 0) {
            // Only send a response if they've specified an id in the call
            sendWebSocketMessage(
                    proxy, responseWrapper(response, id, request.optString("caller", "")));
        }
    }
}
 
Example 10
Source File: DefaultQueryBuilderJsonConfig.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public final Object newInstance(@SuppressWarnings("rawtypes") final Class beanClass, final JSONObject jsonObject) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, InvocationTargetException {
	if(List.class.isAssignableFrom(beanClass)) { 
		return new QueryBuilderGroupNode();
	} else {
		if(jsonObject.optString("condition", null) != null) {
			return new QueryBuilderGroupNode();
		} else {
			return new QueryBuilderRuleNode();
		}
	}
}
 
Example 11
Source File: PolicyRestTest.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void retrievePolicyTest() {
    Response response = target().path("policies/" + encode(policyId.stringValue())).request().get();
    assertEquals(response.getStatus(), 200);
    verify(policyManager).getPolicy(policyId);
    try {
        JSONObject result = JSONObject.fromObject(response.readEntity(String.class));
        String id = result.optString("PolicyId");
        assertNotNull(id);
        assertEquals(id, policyId.stringValue());
    } catch (Exception e) {
        fail("Expected no exception, but got: " + e.getMessage());
    }
}
 
Example 12
Source File: IPCInvokerTaskAnnotationProcessor.java    From IPCInvoker with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(AGContext context, JSONObject env, JavaFileObject javaFileObject, TypeDefineCodeBlock typeDefineCodeBlock, Set<? extends BaseStatement> set) {
    if (typeDefineCodeBlock.getAnnotation(IPCInvokeTask.class.getSimpleName()) == null) {
        Log.i(TAG, "the TypeDefineCodeBlock do not contains 'IPCInvokeTask' annotation.(%s)", javaFileObject.getFileName());
        return false;
    }
    if (set.isEmpty()) {
        Log.i(TAG, "containsSpecialAnnotationStatements is nil");
        return false;
    }
    final String outputDir = env.optString(EnvArgsConstants.KEY_OUTPUT_DIR);
    final String pkg = env.optString(EnvArgsConstants.KEY_PACKAGE);
    final String filePath = env.optString(EnvArgsConstants.KEY_FILE_PATH);

    if (Util.isNullOrNil(outputDir)) {
        Log.i(TAG, "process failed, outputDir is null or nil.(filePath : %s)", filePath);
        return false;
    }

    JavaFileObject fObject = new JavaFileObject();

    fObject.addTypeDefineCodeBlock(createTypeDefineCodeBlock(typeDefineCodeBlock, set));
    fObject.setPackageStatement(javaFileObject.getPackageStatement());
    fObject.copyImports(javaFileObject);
    fObject.attachEnvironmentArgs(javaFileObject.getEnvironmentArgs());

    GenCodeTaskInfo taskInfo = new GenCodeTaskInfo();
    taskInfo.FileName = fObject.getFileName();
    taskInfo.RootDir = Util.joint(File.separator, outputDir, Util.exchangeToPath(pkg));
    taskInfo.javaFileObject = fObject;

    CustomizeGenerator generator = new CodeGenerator(fObject);
    FileOperation.saveToFile(taskInfo, generator.genCode());
    Log.i(TAG, "genCode rootDir : %s, fileName : %s, suffix : %s", taskInfo.RootDir, taskInfo.FileName, taskInfo.Suffix);
    return true;
}
 
Example 13
Source File: IPCInvokeTaskProcessor.java    From IPCInvoker with Apache License 2.0 5 votes vote down vote up
@Override
    public boolean process(AGContext context, JSONObject env, JavaFileObject javaFileObject, TypeDefineCodeBlock typeDefineCodeBlock, Set<? extends BaseStatement> set) {
        if (typeDefineCodeBlock.getAnnotation(IPCInvokeTask.class.getSimpleName()) == null) {
            Log.i(TAG, "the TypeDefineCodeBlock do not contains 'IPCInvokeTask' annotation.(%s)", javaFileObject.getFileName());
            return false;
        }
        if (set.isEmpty()) {
            Log.i(TAG, "containsSpecialAnnotationStatements is nil");
            return false;
        }
        final String outputDir = env.optString(EnvArgsConstants.KEY_OUTPUT_DIR);
        final String pkg = env.optString(EnvArgsConstants.KEY_PACKAGE);
        final String filePath = env.optString(EnvArgsConstants.KEY_FILE_PATH);

        if (Util.isNullOrNil(outputDir)) {
            Log.i(TAG, "process failed, outputDir is null or nil.(filePath : %s)", filePath);
            return false;
        }
        JSONObject args = new JSONObject();
//        args.put("template", "");
        args.put("templateTag", "ipc-invoker-gentask");
        args.put(ArgsConstants.EXTERNAL_ARGS_KEY_DEST_DIR, outputDir);
        args.put("toFile", Util.joint(File.separator, Util.exchangeToPath(pkg),
                String.format("%s$AG.java", typeDefineCodeBlock.getName().getName())));
        args.put("fileObject", javaFileObject.toJSONObject());
        args.put("methodSet", toJSONArray(set));
        context.execProcess("template-processor", args);
        return true;
    }
 
Example 14
Source File: LoadosophiaAPIClient.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
public String startOnline() throws IOException {
    String uri = address + "api/active/receiver/start";
    LinkedList<FormBodyPart> partsList = new LinkedList<>();
    partsList.add(new FormBodyPart("token", new StringBody(token)));
    partsList.add(new FormBodyPart("projectKey", new StringBody(project)));
    partsList.add(new FormBodyPart("title", new StringBody(title)));
    JSONObject obj = queryObject(createPost(uri, partsList), 201);
    return address + "gui/active/" + obj.optString("OnlineID", "N/A") + "/";
}
 
Example 15
Source File: Restore.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
private void restoreRepositories(JSONObject manifest, String backupVersion) throws IOException {

        // Clear populated repositories
        Set<String> remoteRepos = new HashSet<>();
        repositoryManager.getAllRepositories().forEach((repoID, repo) -> {
            if (repo.getConfig() instanceof NativeRepositoryConfig
                    || repo.getConfig() instanceof MemoryRepositoryConfig) {
                try (RepositoryConnection connection = repo.getConnection()) {
                    connection.clear();
                }
            } else {
                remoteRepos.add(repoID);
            }
        });

        // Populate Repositories
        JSONObject repos = manifest.optJSONObject("repositories");
        ImportServiceConfig.Builder builder = new ImportServiceConfig.Builder()
                .continueOnError(false)
                .logOutput(true)
                .printOutput(true)
                .batchSize(batchSize);

        for (Object key : repos.keySet()) {
            String repoName = key.toString();
            if (!remoteRepos.contains(repoName)) {
                String repoPath = repos.optString(key.toString());
                String repoDirectoryPath = repoPath.substring(0, repoPath.lastIndexOf(repoName + ".zip"));
                builder.repository(repoName);
                File repoFile = new File(RESTORE_PATH + File.separator + repoDirectoryPath + File.separator
                        + repoName + ".trig");
                importService.importFile(builder.build(), repoFile);
                LOGGER.trace("Data successfully loaded to " + repoName + " repository.");
                System.out.println("Data successfully loaded to " + repoName + " repository.");
            } else {
                LOGGER.trace("Skipping data load of remote repository " + repoName);
                System.out.println("Skipping data load of remote repository " + repoName);
            }
        }

        // Remove Policy Statements
        RepositoryConnection conn = config.getRepository().getConnection();
        Iterator<Statement> statements = conn.getStatements(null,
                vf.createIRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), vf.createIRI(PolicyFile.TYPE))
                .iterator();

        while (statements.hasNext()) {
            conn.clear(statements.next().getSubject());
        }
        LOGGER.trace("Removed PolicyFile statements");

        if (mobiVersions.indexOf(backupVersion) < 2) {
            // Clear ontology editor state
            statements = conn.getStatements(null,
                    vf.createIRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), vf.createIRI(State.TYPE)).iterator();

            while (statements.hasNext()) {
                stateManager.deleteState(statements.next().getSubject());
            }
            LOGGER.trace("Remove state statements");
        }
    }
 
Example 16
Source File: DingTalkUserProperty.java    From dingtalk-plugin with MIT License 4 votes vote down vote up
@Override
public UserProperty newInstance(@Nullable StaplerRequest req, @Nonnull JSONObject formData) {
  return new DingTalkUserProperty(formData.optString("mobile"));
}
 
Example 17
Source File: WebSocketAPI.java    From zap-extensions with Apache License 2.0 4 votes vote down vote up
@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
    switch (name) {
        case ACTION_SEND_TEXT_MESSAGE:
            try {
                int channelId = params.getInt(PARAM_CHANNEL_ID);
                WebSocketProxy proxy = extension.getWebSocketProxy(channelId);
                if (proxy != null) {
                    this.sendWebSocketMessage(
                            proxy,
                            params.getBoolean(PARAM_OUTGOING),
                            params.getString(PARAM_MESSAGE));
                } else {
                    throw new ApiException(
                            ApiException.Type.DOES_NOT_EXIST, "channelId: " + channelId);
                }
            } catch (IOException e) {
                LOG.warn(e.getMessage(), e);
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
            break;

        case ACTION_SET_BREAK_TEXT_MESSAGE:
            ExtensionBreak extBreak =
                    Control.getSingleton()
                            .getExtensionLoader()
                            .getExtension(ExtensionBreak.class);
            if (extBreak == null) {
                throw new ApiException(
                        ApiException.Type.INTERNAL_ERROR, "ExtensionBreak not present");
            }
            Message msg = extBreak.getBreakpointManagementInterface().getMessage();

            if (msg == null) {
                throw new ApiException(
                        ApiException.Type.ILLEGAL_PARAMETER,
                        "No currently intercepted message");
            } else if (msg instanceof WebSocketMessageDTO) {
                WebSocketMessageDTO ws = (WebSocketMessageDTO) msg;
                ws.payload = params.optString(PARAM_MESSAGE, "");
                extBreak.getBreakpointManagementInterface()
                        .setMessage(ws, params.getBoolean(PARAM_OUTGOING));
            } else {
                throw new ApiException(
                        ApiException.Type.ILLEGAL_PARAMETER,
                        "Intercepted message is not of the right type "
                                + msg.getClass().getCanonicalName());
            }
            break;

        default:
            throw new ApiException(ApiException.Type.BAD_ACTION);
    }

    return ApiResponseElement.OK;
}
 
Example 18
Source File: SemanticVersionColumn.java    From semantic-versioning-plugin with MIT License 4 votes vote down vote up
@Override
public ListViewColumn newInstance(StaplerRequest req, JSONObject formData) throws FormException {
    String strategy = formData == null ? null : formData.optString("displayStrategy");
    return new SemanticVersionColumn(StringUtils.defaultIfBlank(strategy,
            LastSuccessfulBuildStrategy.class.getCanonicalName()));
}
 
Example 19
Source File: PolicyEnforcementRest.java    From mobi with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Converts a user provided JSON object string into a XACML request. Evaluates the request and returns the decision
 * result. An example request would have a JSON object of:
 * {
 *     "resourceId": "http://mobi.com/catalog-local",
 *     "actionId": "http://mobi.com/ontologies/policy#Create",
 *     "actionAttrs": {
 *     "http://www.w3.org/1999/02/22-rdf-syntax-ns#type":"http://mobi.com/ontologies/ontology-editor#OntologyRecord"
 *     }
 * }
 *
 * @param context the request context supplied by the underlying JAX-RS implementation
 * @param jsonRequest a JSON object containing XACML required fields
 * @return the decision of the XACML request evaluation
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
@RolesAllowed("user")
@ApiOperation("Converts user provided request into XACML and evaluates.")
public Response evaluateRequest(@Context ContainerRequestContext context, String jsonRequest) {
    log.debug("Authorizing...");
    long start = System.currentTimeMillis();

    try {
        JSONObject json = JSONObject.fromObject(jsonRequest);
        IRI subjectId = (IRI) RestUtils.optActiveUser(context, engineManager).map(User::getResource)
                .orElse(vf.createIRI(ANON_USER));

        String actionIdStr = json.optString("actionId");
        String resourceIdStr = json.optString("resourceId");
        if (StringUtils.isEmpty(actionIdStr) || StringUtils.isEmpty(resourceIdStr)) {
            throw ErrorUtils.sendError("ID is required.", Response.Status.BAD_REQUEST);
        }

        IRI actionId = vf.createIRI(actionIdStr);
        IRI resourceId = vf.createIRI(resourceIdStr);

        Map<String, String> attributes = json.getJSONObject("subjectAttrs");
        Map<String, Literal> subjectAttrs = attributes.entrySet().stream().collect(Collectors.toMap(
                e -> e.getKey(), e -> vf.createLiteral(e.getValue())));
        attributes = json.getJSONObject("resourceAttrs");
        Map<String, Literal> resourceAttrs = attributes.entrySet().stream().collect(Collectors.toMap(
                e -> e.getKey(), e -> vf.createLiteral(e.getValue())));
        attributes = json.getJSONObject("actionAttrs");
        Map<String, Literal> actionAttrs = attributes.entrySet().stream().collect(Collectors.toMap(
                e -> e.getKey(), e -> vf.createLiteral(e.getValue())));

        Request request = pdp.createRequest(subjectId, subjectAttrs, resourceId, resourceAttrs,
                actionId, actionAttrs);

        log.debug(request.toString());
        com.mobi.security.policy.api.Response response = pdp.evaluate(request,
                vf.createIRI(POLICY_PERMIT_OVERRIDES));
        log.debug(response.toString());
        log.debug(String.format("Request Evaluated. %dms", System.currentTimeMillis() - start));

        return Response.ok(response.getDecision().toString()).build();
    } catch (IllegalArgumentException | MobiException ex) {
        throw ErrorUtils.sendError("Request could not be evaluated", Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example 20
Source File: JsonSecurityRule.java    From ipst with Mozilla Public License 2.0 4 votes vote down vote up
private static boolean isTrueCondition(JSONObject stats, JSONObject node, double purityThreshold, int trueIdx) {
    String nodeIdx = node.optString("id");
    JSONArray nodeValues = stats.optJSONObject(nodeIdx).optJSONArray("counts");
    double purity = ((double) nodeValues.optInt(trueIdx)) / stats.optJSONObject(nodeIdx).optInt("count");
    return purity >= purityThreshold && node.optBoolean("value");
}