Java Code Examples for com.github.openjson.JSONObject#put()
The following examples show how to use
com.github.openjson.JSONObject#put() .
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: Client.java From openmeetings with Apache License 2.0 | 6 votes |
private JSONObject addUserJson(JSONObject o) { JSONObject u = new JSONObject(); if (user != null) { JSONObject a = new JSONObject(); u.put("id", user.getId()) .put("firstName", user.getFirstname()) .put("lastName", user.getLastname()) .put("displayName", user.getDisplayName()) .put("address", a) .put("pictureUri", pictureUri); if (user.getAddress() != null) { if (Strings.isEmpty(user.getFirstname()) && Strings.isEmpty(user.getLastname())) { a.put("email", user.getAddress().getEmail()); } a.put("country", user.getAddress().getCountry()); } } return o.put("user", u) .put("level", hasRight(Right.MODERATOR) ? 5 : (hasRight(Right.WHITEBOARD) ? 3 : 1)); }
Example 2
Source File: Whiteboard.java From openmeetings with Apache License 2.0 | 6 votes |
public JSONObject toJson() { //deep-copy JSONObject json = new JSONObject(new JSONObject(this).toString(new NullStringer())); json.remove("id"); //filtering json.remove("empty"); //filtering JSONObject items = new JSONObject(); for (Entry<String, String> e : roomItems.entrySet()) { JSONObject o = new JSONObject(e.getValue()); //filtering if ("Clipart".equals(o.opt(ATTR_OMTYPE))) { if (o.has(PARAM__SRC)) { o.put(PARAM_SRC, o.get(PARAM__SRC)); } } else { o.remove(PARAM_SRC); } o.remove(PARAM__SRC); items.put(e.getKey(), o); } json.put(ITEMS_KEY, items); return json; }
Example 3
Source File: WbConverter.java From openmeetings with Apache License 2.0 | 6 votes |
private static void processText(Whiteboard wb, List<?> props) { if (props.size() < 12) { return; } String color = getColor(getInt(props, 2)); String style = (String)props.get(4); JSONObject o = setColor(init(wb, props), color, color) .put(ATTR_TYPE, "i-text") .put("text", props.get(1)) .put("fontSize", props.get(3)); if (style.indexOf("bold") > -1) { o.put("fontWeight", "bold"); } if (style.indexOf("italic") > -1) { o.put("fontStyle", "inalic"); } add(wb, o); }
Example 4
Source File: NetTestPanel.java From openmeetings with Apache License 2.0 | 6 votes |
private JSONObject getStringLabels() { JSONObject o = new JSONObject(); for (String id : new String[] {"network.test.ms", "network.test.mb", "network.test.sec" , "network.test.click.play", "network.test.copy.log", "network.test.report.start" , "network.test.ping", "network.test.ping.avg", "network.test.ping.rcv" , "network.test.ping.lost", "network.test.ping.load" , "network.test.port", "network.test.port.avail", "network.test.port.stopped" , "network.test.jitter", "network.test.jitter.avg", "network.test.jitter.min" , "network.test.jitter.max", "network.test.jitter.avgAbbr" , "network.test.dwn", "network.test.dwn.bytes", "network.test.dwn.time" , "network.test.dwn.speed" , "network.test.upl", "network.test.upl.bytes", "network.test.upl.time" , "network.test.upl.speed"}) { o.put(id.substring("network.test.".length()), getString(id)); } return o; }
Example 5
Source File: WbWebSocketHelper.java From openmeetings with Apache License 2.0 | 6 votes |
private static JSONObject patchUrls(BaseFileItem fi, Client c, JSONObject _f) { JSONObject f = new JSONObject(_f.toString()); // deep copy to ensure thread safety switch (fi.getType()) { case VIDEO: f.put(PARAM__SRC, patchUrl(f.getString(PARAM__SRC), c)); f.put(PARAM__POSTER, patchUrl(f.getString(PARAM__POSTER), c)); break; case RECORDING: f.put(PARAM__SRC, patchUrl(f.getString(PARAM__SRC), c)); f.put(PARAM__POSTER, patchUrl(f.getString(PARAM__POSTER), c)); break; case PRESENTATION: f.put(PARAM__SRC, patchUrl(f.getString(PARAM__SRC), c)); break; default: f.put(PARAM_SRC, patchUrl(f.getString(PARAM_SRC), c)); break; } return f; }
Example 6
Source File: ODateField.java From Orienteer with Apache License 2.0 | 5 votes |
private JSONObject getDatePickerParams() { JSONObject params = new JSONObject(); params.put("autoclose", Boolean.toString(true)); params.put("language", getLocale().getLanguage()); params.put("orientation", "bottom"); params.put("weekStart", Integer.toString(1)); params.put("format", getJavaScriptDatePattern()); return params; }
Example 7
Source File: LegacyRemoteApiController.java From webanno with Apache License 2.0 | 5 votes |
/** * List all the projects for a given user with their roles * * Test when running in Eclipse: Open your browser, paste following URL with appropriate values * for username and password: * * http://USERNAME:PASSWORD@localhost:8080/webanno-webapp/api/projects * * @return JSON string of project where user has access to and respective roles in the project. * @throws Exception * if there was an error. */ @RequestMapping( value = ("/" + PROJECTS), method = RequestMethod.GET) public ResponseEntity<String> projectList() throws Exception { // Get current user String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.get(username); if (user == null) { return ResponseEntity .badRequest() .body("User [" + username + "] not found."); } // Get projects with permission List<Project> accessibleProjects = projectRepository.listAccessibleProjects(user); // Add permissions for each project into JSON array and store in JSON object JSONObject returnJSONObj = new JSONObject(); for (Project project : accessibleProjects) { String projectId = Long.toString(project.getId()); List<ProjectPermission> projectPermissions = projectRepository .listProjectPermissionLevel(user, project); JSONArray permissionArr = new JSONArray(); JSONObject projectJSON = new JSONObject(); for (ProjectPermission p : projectPermissions) { permissionArr.put(p.getLevel().getName()); } projectJSON.put(project.getName(), permissionArr); returnJSONObj.put(projectId, projectJSON); } return ResponseEntity.ok(returnJSONObj.toString()); }
Example 8
Source File: MatomoTelemetrySupportImpl.java From webanno with Apache License 2.0 | 5 votes |
private void sendTelemetry(String aAction) { if (tracker == null) { log.debug("Telemetry unavailable"); return; } InstanceIdentity id = identityService.getInstanceIdentity(); UUID uuid = UUID.fromString(id.getId()); JSONObject payload = new JSONObject(); payload.put("1", new JSONArray(asList("app", applicationName))); payload.put("2", new JSONArray(asList("version", getVersionProperties().getProperty(PROP_VERSION)))); payload.put("3", new JSONArray( asList("activeUsers", String.valueOf(sessionRegistry.getAllPrincipals().size())))); payload.put("4", new JSONArray( asList("enabledUsers", String.valueOf(userService.listEnabledUsers().size())))); payload.put("5", new JSONArray( asList("deploymentMode", telemetryService.getDeploymentMode().toString()))); PiwikRequest request = PiwikRequest.builder() .url(TELEMETRY_CONTEXT) .putParameter(HEADER_USER_AGENT, System.getProperty("os.name")) .putParameter(ACTION_NAME, aAction) .putParameter(VISITOR_ID, Long.toHexString(uuid.getMostSignificantBits())) .putParameter(USER_ID, id.getId()) .putParameter(VISIT_CUSTOM_VARIABLE, payload.toString()) .build(); boolean success = tracker.send(request); if (success) { log.debug("Telemetry sent ({})", aAction); } else { log.debug("Unable to reach telemetry server"); } }
Example 9
Source File: WbWebSocketHelper.java From openmeetings with Apache License 2.0 | 5 votes |
public static JSONObject addFileUrl(String ruid, JSONObject _file, BaseFileItem fi, Client c) { JSONObject file = new JSONObject(_file.toString(new NullStringer())); final FileSystemResourceReference ref; final PageParameters pp = new PageParameters() .add("id", fi.getId()) .add("ruid", ruid) .add("wuid", _file.optString("uid")); if (c != null) { pp.add("uid", c.getUid()); } file.put("deleted", !fi.exists()); switch (fi.getType()) { case VIDEO: ref = new RoomResourceReference(); file.put(PARAM__SRC, urlFor(ref, pp)); file.put(PARAM__POSTER, urlFor(new RoomPreviewResourceReference(), pp)); break; case RECORDING: ref = new Mp4RecordingResourceReference(); file.put(PARAM__SRC, urlFor(ref, pp)); file.put(PARAM__POSTER, urlFor(new PngRecordingResourceReference(), pp)); break; case PRESENTATION: ref = new RoomResourceReference(); file.put(PARAM__SRC, urlFor(ref, pp)); break; default: ref = new RoomResourceReference(); file.put(PARAM_SRC, urlFor(ref, pp)); break; } return file; }
Example 10
Source File: QuickPollManager.java From openmeetings with Apache License 2.0 | 5 votes |
public JSONObject toJson(Long roomId) { boolean started = isStarted(roomId); JSONObject o = new JSONObject().put("started", started); if (started) { Map<Long, Boolean> votes = map().get(roomId); o.put("voted", votes.containsKey(getUserId())); o.put("pros", votes.entrySet().stream().filter(Entry::getValue).count()) .put("cons", votes.entrySet().stream().filter(e -> !e.getValue()).count()); } return o; }
Example 11
Source File: ChatWebSocketHelper.java From openmeetings with Apache License 2.0 | 5 votes |
private static JSONObject setScope(JSONObject o, ChatMessage m, long curUserId) { String scope, scopeName = null; if (m.getToUser() != null) { User u = curUserId == m.getToUser().getId() ? m.getFromUser() : m.getToUser(); scope = ID_USER_PREFIX + u.getId(); scopeName = u.getDisplayName(); } else if (m.getToRoom() != null) { scope = ID_ROOM_PREFIX + m.getToRoom().getId(); o.put("needModeration", m.isNeedModeration()); } else { scope = ID_ALL; } return o.put("scope", scope).put("scopeName", scopeName); }
Example 12
Source File: ActivitiesPanel.java From openmeetings with Apache License 2.0 | 4 votes |
public void add(Activity a, IPartialPageRequestHandler handler) { if (!isVisible()) { return; } final boolean self = getUserId().equals(a.getSender()); if (shouldSkip(self, a)) { return; } if (a.getType().isAction()) { remove(handler, activities.entrySet().parallelStream() .filter(e -> a.getSender().equals(e.getValue().getSender()) && a.getType() == e.getValue().getType()) .map(e -> e.getValue().getId()) .toArray(String[]::new)); } activities.put(a.getId(), a); String text = ""; final String name = self ? getString("1362") : a.getName(); final String fmt = ((BasePage)getPage()).isRtl() ? ACTIVITY_FMT_RTL : ACTIVITY_FMT; switch (a.getType()) { case roomEnter: text = String.format(fmt, name, getString("activities.msg.enter"), df.format(a.getCreated())); break; case roomExit: text = String.format(fmt, name, getString("activities.msg.exit"), df.format(a.getCreated())); break; case reqRightModerator: text = String.format(fmt, name, getString("activities.request.right.moderator"), df.format(a.getCreated())); break; case reqRightPresenter: text = String.format(fmt, name, getString("activities.request.right.presenter"), df.format(a.getCreated())); break; case reqRightWb: text = String.format(fmt, name, getString("activities.request.right.wb"), df.format(a.getCreated())); break; case reqRightShare: text = String.format(fmt, name, getString("activities.request.right.share"), df.format(a.getCreated())); break; case reqRightRemote: text = String.format(fmt, name, getString("activities.request.right.remote"), df.format(a.getCreated())); break; case reqRightA: text = String.format(fmt, name, getString("activities.request.right.audio"), df.format(a.getCreated())); break; case reqRightAv: text = String.format(fmt, name, getString("activities.request.right.video"), df.format(a.getCreated())); break; case reqRightMuteOthers: text = String.format(fmt, name, getString("activities.request.right.muteothers"), df.format(a.getCreated())); break; case haveQuestion: text = String.format(fmt, name, getString("activities.ask.question"), df.format(a.getCreated())); break; } final JSONObject aobj = new JSONObject() .put("id", a.getId()) .put("uid", a.getUid()) .put("cssClass", getClass(a)) .put("text", text) .put("action", a.getType().isAction()) .put("find", false); switch (a.getType()) { case reqRightModerator: case reqRightPresenter: case reqRightWb: case reqRightShare: case reqRightRemote: case reqRightA: case reqRightAv: case reqRightMuteOthers: aobj.put("accept", room.getClient().hasRight(Right.MODERATOR)); aobj.put("decline", room.getClient().hasRight(Right.MODERATOR)); break; case haveQuestion: aobj.put("find", !self); case roomEnter: case roomExit: aobj.put("accept", false); aobj.put("decline", false); break; } handler.appendJavaScript(new StringBuilder("Activities.add(").append(aobj.toString()).append(");")); }
Example 13
Source File: WbPanel.java From openmeetings with Apache License 2.0 | 4 votes |
private void sendFileToWb(Long wbId, final BaseFileItem fi, boolean clean) { if (isVisible() && fi.getId() != null) { Whiteboards wbs = wbm.get(roomId); String wuid = randomUUID().toString(); Whiteboard wb = wbs.get(wbId == null ? wbs.getActiveWb() : wbId); if (wb == null) { return; } switch (fi.getType()) { case FOLDER: //do nothing break; case WML_FILE: { File f = fi.getFile(); if (f.exists() && f.isFile()) { try (BufferedReader br = Files.newBufferedReader(f.toPath())) { final boolean[] updated = {false}; JSONArray arr = getArray(new JSONObject(new JSONTokener(br)), o -> { wb.put(o.getString("uid"), o); updated[0] = true; return addFileUrl(rp.getClient(), wbs.getUid(), o, bf -> updateWbSize(wb, bf)); }); if (updated[0]) { wbm.update(roomId, wb); } sendWbAll(WbAction.setSize, wb.getAddJson()); sendWbAll(WbAction.load, getObjWbJson(wb.getId(), arr)); } catch (Exception e) { log.error("Unexpected error while loading WB", e); } } } break; case POLL_CHART: break; default: { JSONObject file = new JSONObject() .put(ATTR_FILE_ID, fi.getId()) .put(ATTR_FILE_TYPE, fi.getType().name()) .put("count", fi.getCount()) .put(ATTR_TYPE, "image") .put("left", UPLOAD_WB_LEFT) .put("top", UPLOAD_WB_TOP) .put(ATTR_WIDTH, fi.getWidth() == null ? DEFAULT_WIDTH : fi.getWidth()) .put(ATTR_HEIGHT, fi.getHeight() == null ? DEFAULT_HEIGHT : fi.getHeight()) .put("uid", wuid) .put(ATTR_SLIDE, wb.getSlide()) ; if (FileItem.Type.VIDEO == fi.getType() || FileItem.Type.RECORDING == fi.getType()) { file.put(ATTR_OMTYPE, "Video"); file.put(PARAM_STATUS, new JSONObject() .put("paused", true) .put("pos", 0.0) .put(PARAM_UPDATED, System.currentTimeMillis())); } final String ruid = wbs.getUid(); if (clean) { wbm.clearAll(roomId, wb.getId(), addUndo); } wb.put(wuid, file); updateWbSize(wb, fi); wbm.update(roomId, wb); sendWbAll(WbAction.setSize, wb.getAddJson()); WbWebSocketHelper.sendWbFile(roomId, wb.getId(), ruid, file, fi); } break; } } }
Example 14
Source File: KurentoHandler.java From openmeetings with Apache License 2.0 | 4 votes |
JSONArray getTurnServers(Client c, final boolean test) { JSONArray arr = new JSONArray(); if (!Strings.isEmpty(turnUrl)) { try { JSONObject turn = new JSONObject(); if ("rest".equalsIgnoreCase(turnMode)) { Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(new SecretKeySpec(turnSecret.getBytes(), HMAC_SHA1_ALGORITHM)); StringBuilder user = new StringBuilder() .append((test ? 60 : turnTtl * 60) + System.currentTimeMillis() / 1000L); final String uid = c == null ? null : c.getUid(); if (!Strings.isEmpty(uid)) { user.append(':').append(uid); } else if (!Strings.isEmpty(turnUser)) { user.append(':').append(turnUser); } turn.put("username", user) .put("credential", Base64.getEncoder().encodeToString(mac.doFinal(user.toString().getBytes()))); } else { turn.put("username", turnUser) .put("credential", turnSecret); } JSONArray urls = new JSONArray(); final String[] turnUrls = turnUrl.split(","); for (String url : turnUrls) { if (url.startsWith("stun:") || url.startsWith("stuns:") || url.startsWith("turn:") || url.startsWith("turns:")) { urls.put(url); } else { urls.put("turn:" + url); } } turn.put("urls", urls); arr.put(turn); } catch (NoSuchAlgorithmException|InvalidKeyException e) { log.error("Unexpected error while creating turn", e); } } return arr; }
Example 15
Source File: LegacyRemoteApiController.java From webanno with Apache License 2.0 | 4 votes |
/** * Show source documents in given project where user has ADMIN access * * http://USERNAME:PASSWORD@localhost:8080/webanno-webapp/api/projects/{aProjectId}/sourcedocs * * @param aProjectId the project ID * @return JSON with {@link SourceDocument} : id */ @RequestMapping( value = "/" + PROJECTS + "/{" + PARAM_PROJECT_ID + "}/" + DOCUMENTS, method = RequestMethod.GET) public ResponseEntity<String> sourceDocumentList( @PathVariable(PARAM_PROJECT_ID) long aProjectId) throws Exception { // Get current user String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.get(username); if (user == null) { return ResponseEntity .badRequest() .body("User [" + username + "] not found."); } // Get project Project project; try { project = projectRepository.getProject(aProjectId); } catch (NoResultException e) { return ResponseEntity .status(HttpStatus.NOT_FOUND) .body("Project [" + aProjectId + "] not found."); } // Check for the access boolean hasAccess = projectRepository.isManager(project, user) || userRepository.isAdministrator(user); if (!hasAccess) { return ResponseEntity.status(HttpStatus.FORBIDDEN).body("User [" + username + "] is not allowed to access project [" + aProjectId + "]"); } List<SourceDocument> srcDocumentList = documentRepository.listSourceDocuments(project); JSONArray sourceDocumentJSONArr = new JSONArray(); for (SourceDocument s : srcDocumentList) { JSONObject sourceDocumentJSONObj = new JSONObject(); sourceDocumentJSONObj.put("id", s.getId()); sourceDocumentJSONObj.put("name", s.getName()); sourceDocumentJSONObj.put("state", s.getState()); sourceDocumentJSONArr.put(sourceDocumentJSONObj); } return ResponseEntity.ok(sourceDocumentJSONArr.toString()); }
Example 16
Source File: LegacyRemoteApiController.java From webanno with Apache License 2.0 | 4 votes |
/** * Upload a source document into project where user has "ADMIN" role * * Test when running in Eclipse, use the Linux "curl" command. * * curl -v -F '[email protected]' -F 'filetype=text' * 'http://USERNAME:PASSWORD@localhost:8080/webanno-webapp/api/projects/{aProjectId}/sourcedocs/ * ' * * @param aFile * File for {@link SourceDocument}. * @param aProjectId * {@link Project} id. * @param aFileType * Extension of the file. * @return returns JSON string with id to the created source document. * @throws Exception * if there was an error. */ @RequestMapping( value = "/" + PROJECTS + "/{" + PARAM_PROJECT_ID + "}/" + DOCUMENTS, method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<String> sourceDocumentCreate( @RequestParam(PARAM_FILE) MultipartFile aFile, @RequestParam(PARAM_FILETYPE) String aFileType, @PathVariable(PARAM_PROJECT_ID) long aProjectId) throws Exception { // Get current user String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.get(username); if (user == null) { return ResponseEntity .badRequest() .body("User [" + username + "] not found."); } // Get project Project project; try { project = projectRepository.getProject(aProjectId); } catch (NoResultException e) { return ResponseEntity .status(HttpStatus.NOT_FOUND) .body("Project [" + aProjectId + "] not found."); } // Check for the access boolean hasAccess = projectRepository.isManager(project, user) || userRepository.isAdministrator(user); if (!hasAccess) { return ResponseEntity.status(HttpStatus.FORBIDDEN).body("User [" + username + "] is not allowed to access project [" + aProjectId + "]"); } // Existing project if (documentRepository.existsSourceDocument(project, aFile.getOriginalFilename())) { return ResponseEntity .status(HttpStatus.CONFLICT) .body("A document with name [" + aFile.getOriginalFilename() + "] already exists"); } // Check if file already present or not try (InputStream is = aFile.getInputStream()) { uploadSourceDocumentFile(is,aFile.getOriginalFilename(), project, aFileType); } // add id of added source document in return json string JSONObject returnJSON = new JSONObject(); returnJSON.put("id", documentRepository.getSourceDocument(project, aFile.getOriginalFilename()).getId()); return ResponseEntity.ok(returnJSON.toString()); }
Example 17
Source File: MtasDocumentIndex.java From inception with Apache License 2.0 | 4 votes |
private synchronized IndexWriter getIndexWriter() throws IOException { if (_indexWriter == null) { log.debug("Opening index for project [{}]({})", project.getName(), project.getId()); OPEN_INDEXES.put(project.getId(), this); // Initialize and populate the hash maps for the layers and features features = schemaService.listAnnotationFeature(project).stream() .filter(feat -> feat.getLayer().isEnabled()) .filter(feat -> feat.isEnabled()) .collect(Collectors.toList()); // Add the project id to the configuration JSONObject jsonParserConfiguration = new JSONObject(); jsonParserConfiguration.put(PARAM_PROJECT_ID, project.getId()); // Tokenizer parameters Map<String, String> tokenizerArguments = new HashMap<>(); tokenizerArguments.put(ARGUMENT_PARSER, MtasUimaParser.class.getName()); tokenizerArguments.put(ARGUMENT_PARSER_ARGS, jsonParserConfiguration.toString()); // Build analyzer Analyzer mtasAnalyzer = CustomAnalyzer.builder() .withTokenizer(MtasTokenizerFactory.class, tokenizerArguments) .build(); Map<String, Analyzer> analyzerPerField = new HashMap<String, Analyzer>(); analyzerPerField.put(FIELD_CONTENT, mtasAnalyzer); PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new StandardAnalyzer(), analyzerPerField); // Build IndexWriter FileUtils.forceMkdir(getIndexDir()); IndexWriterConfig config = new IndexWriterConfig(analyzer); config.setCodec(Codec.forName(MTAS_CODEC_NAME)); IndexWriter indexWriter = new IndexWriter(FSDirectory.open(getIndexDir().toPath()), config); // Initialize the index indexWriter.commit(); // After the index has been initialized, assign the _indexWriter - this is also used // by isOpen() to check if the index writer is available. _indexWriter = indexWriter; } return _indexWriter; }