List of usage examples for org.json.simple JSONObject toString
@Override
public String toString()
From source file:org.alfresco.repo.web.scripts.node.NodeWebScripTest.java
@SuppressWarnings("unchecked") public void testFolderCreation() throws Exception { // Create a folder within the DocLib NodeRef siteDocLib = siteService.getContainer(TEST_SITE.getShortName(), SiteService.DOCUMENT_LIBRARY); String testFolderName = "testing"; Map<QName, Serializable> testFolderProps = new HashMap<QName, Serializable>(); testFolderProps.put(ContentModel.PROP_NAME, testFolderName); NodeRef testFolder = nodeService.createNode(siteDocLib, ContentModel.ASSOC_CONTAINS, QName.createQName("testing"), ContentModel.TYPE_FOLDER, testFolderProps).getChildRef(); String testNodeName = "aNEWfolder"; String testNodeTitle = "aTITLEforAfolder"; String testNodeDescription = "DESCRIPTIONofAfolder"; JSONObject jsonReq = null; JSONObject json = null;/*from ww w. ja v a 2s .c o m*/ NodeRef folder = null; // By NodeID Request req = new Request("POST", "/api/node/folder/" + testFolder.getStoreRef().getProtocol() + "/" + testFolder.getStoreRef().getIdentifier() + "/" + testFolder.getId()); jsonReq = new JSONObject(); jsonReq.put("name", testNodeName); req.setBody(jsonReq.toString().getBytes()); req.setType(MimetypeMap.MIMETYPE_JSON); json = asJSON(sendRequest(req, Status.STATUS_OK)); assertNotNull(json.get("nodeRef")); folder = new NodeRef((String) json.get("nodeRef")); assertEquals(true, nodeService.exists(folder)); assertEquals(testNodeName, nodeService.getProperty(folder, ContentModel.PROP_NAME)); assertEquals(testNodeName, nodeService.getProperty(folder, ContentModel.PROP_TITLE)); assertEquals(null, nodeService.getProperty(folder, ContentModel.PROP_DESCRIPTION)); assertEquals(testFolder, nodeService.getPrimaryParent(folder).getParentRef()); assertEquals(ContentModel.TYPE_FOLDER, nodeService.getType(folder)); nodeService.deleteNode(folder); // In a Site Container req = new Request("POST", "/api/site/folder/" + TEST_SITE_NAME + "/" + SiteService.DOCUMENT_LIBRARY); jsonReq = new JSONObject(); jsonReq.put("name", testNodeName); jsonReq.put("description", testNodeDescription); req.setBody(jsonReq.toString().getBytes()); json = asJSON(sendRequest(req, Status.STATUS_OK)); assertNotNull(json.get("nodeRef")); folder = new NodeRef((String) json.get("nodeRef")); assertEquals(true, nodeService.exists(folder)); assertEquals(testNodeName, nodeService.getProperty(folder, ContentModel.PROP_NAME)); assertEquals(testNodeName, nodeService.getProperty(folder, ContentModel.PROP_TITLE)); assertEquals(testNodeDescription, nodeService.getProperty(folder, ContentModel.PROP_DESCRIPTION)); assertEquals(siteDocLib, nodeService.getPrimaryParent(folder).getParentRef()); assertEquals(ContentModel.TYPE_FOLDER, nodeService.getType(folder)); nodeService.deleteNode(folder); // A Child of a Site Container req = new Request("POST", "/api/site/folder/" + TEST_SITE_NAME + "/" + SiteService.DOCUMENT_LIBRARY + "/" + testFolderName); jsonReq = new JSONObject(); jsonReq.put("name", testNodeName); jsonReq.put("title", testNodeTitle); jsonReq.put("description", testNodeDescription); req.setBody(jsonReq.toString().getBytes()); json = asJSON(sendRequest(req, Status.STATUS_OK)); assertNotNull(json.get("nodeRef")); folder = new NodeRef((String) json.get("nodeRef")); assertEquals(true, nodeService.exists(folder)); assertEquals(testNodeName, nodeService.getProperty(folder, ContentModel.PROP_NAME)); assertEquals(testNodeTitle, nodeService.getProperty(folder, ContentModel.PROP_TITLE)); assertEquals(testNodeDescription, nodeService.getProperty(folder, ContentModel.PROP_DESCRIPTION)); assertEquals(testFolder, nodeService.getPrimaryParent(folder).getParentRef()); assertEquals(ContentModel.TYPE_FOLDER, nodeService.getType(folder)); nodeService.deleteNode(folder); // Type needs to be a subtype of folder // explicit cm:folder req = new Request("POST", "/api/site/folder/" + TEST_SITE_NAME + "/" + SiteService.DOCUMENT_LIBRARY + "/" + testFolderName); jsonReq = new JSONObject(); jsonReq.put("name", testNodeName); jsonReq.put("type", "cm:folder"); req.setBody(jsonReq.toString().getBytes()); json = asJSON(sendRequest(req, Status.STATUS_OK)); assertNotNull(json.get("nodeRef")); folder = new NodeRef((String) json.get("nodeRef")); assertEquals(true, nodeService.exists(folder)); assertEquals(testNodeName, nodeService.getProperty(folder, ContentModel.PROP_NAME)); assertEquals(ContentModel.TYPE_FOLDER, nodeService.getType(folder)); nodeService.deleteNode(folder); // cm:systemfolder extends from cm:folder req = new Request("POST", "/api/site/folder/" + TEST_SITE_NAME + "/" + SiteService.DOCUMENT_LIBRARY + "/" + testFolderName); jsonReq = new JSONObject(); jsonReq.put("name", testNodeName); jsonReq.put("type", "cm:systemfolder"); req.setBody(jsonReq.toString().getBytes()); json = asJSON(sendRequest(req, Status.STATUS_OK)); assertNotNull(json.get("nodeRef")); folder = new NodeRef((String) json.get("nodeRef")); assertEquals(true, nodeService.exists(folder)); assertEquals(testNodeName, nodeService.getProperty(folder, ContentModel.PROP_NAME)); assertEquals(ContentModel.TYPE_SYSTEM_FOLDER, nodeService.getType(folder)); nodeService.deleteNode(folder); // cm:content isn't allowed req = new Request("POST", "/api/site/folder/" + TEST_SITE_NAME + "/" + SiteService.DOCUMENT_LIBRARY + "/" + testFolderName); jsonReq = new JSONObject(); jsonReq.put("name", testNodeName); jsonReq.put("type", "cm:content"); req.setBody(jsonReq.toString().getBytes()); sendRequest(req, Status.STATUS_BAD_REQUEST); // Check permissions - need to be Contributor AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE); req = new Request("POST", "/api/node/folder/" + testFolder.getStoreRef().getProtocol() + "/" + testFolder.getStoreRef().getIdentifier() + "/" + testFolder.getId()); jsonReq = new JSONObject(); jsonReq.put("name", testNodeName); req.setBody(jsonReq.toString().getBytes()); req.setType(MimetypeMap.MIMETYPE_JSON); json = asJSON(sendRequest(req, Status.STATUS_OK)); assertNotNull(json.get("nodeRef")); folder = new NodeRef((String) json.get("nodeRef")); assertEquals(true, nodeService.exists(folder)); nodeService.deleteNode(folder); AuthenticationUtil.setFullyAuthenticatedUser(USER_TWO); sendRequest(req, Status.STATUS_FORBIDDEN); }
From source file:org.alfresco.rest.api.impl.node.ratings.AbstractRatingScheme.java
protected void postActivity(final NodeRef nodeRef, final String activityType) { String siteId = getSiteId(nodeRef); JSONObject activityData = getActivityData(nodeRef, siteId); if (activityData != null) { activityService.postActivity(activityType, siteId, "nodeRatings", activityData.toString(), Client.asType(Client.ClientType.restapi)); }//w w w. j a va 2 s . co m }
From source file:org.alfresco.rest.api.tests.RepoService.java
public void postActivity(final String activityType, final String siteId, final JSONObject activityData) throws JobExecutionException { activityService.postActivity(activityType, siteId, "documentlibrary", activityData.toString()); }
From source file:org.alfresco.test.util.AlfrescoHttpClient.java
/** * Populate HTTP message call with given content. * /* ww w . java2s. com*/ * @param json {@link JSONObject} content * @return {@link StringEntity} content. * @throws UnsupportedEncodingException if unsupported */ public StringEntity setMessageBody(final JSONObject json) throws UnsupportedEncodingException { if (json == null || json.toString().isEmpty()) { throw new IllegalArgumentException("JSON Content is required."); } StringEntity se = new StringEntity(json.toString(), UTF_8_ENCODING); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, MIME_TYPE_JSON)); if (logger.isDebugEnabled()) { logger.debug("Json string value: " + se); } return se; }
From source file:org.alfresco.test.util.SiteService.java
/** * Add pages to site dashboard//from w w w . j ava2 s. c om * * @param userName String identifier * @param password * @param siteName * @param multiplePages * @param page - single page to be added * @param pages - list of pages to be added * @return true if the page is added * @throws Exception if error */ private boolean addPages(final String userName, final String password, final String siteName, final boolean multiplePages, final Page page, final List<Page> pages) throws Exception { if (!exists(siteName, userName, password)) { throw new RuntimeException("Site doesn't exists " + siteName); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); String url = client.getAlfrescoUrl() + DashboardCustomization.SITE_PAGES_URL; org.json.JSONObject body = new org.json.JSONObject(); org.json.JSONArray array = new org.json.JSONArray(); body.put("siteId", siteName); // set the default page (Document Library) array.put(new org.json.JSONObject().put("pageId", Page.DOCLIB.pageId)); if (pages != null) { for (int i = 0; i < pages.size(); i++) { if (!Page.DOCLIB.pageId.equals(pages.get(i).pageId)) { array.put(new org.json.JSONObject().put("pageId", pages.get(i).pageId)); } } } // add the new page if (!multiplePages) { array.put(new org.json.JSONObject().put("pageId", page.pageId)); } body.put("pages", array); body.put("themeId", ""); HttpPost post = new HttpPost(url); StringEntity se = new StringEntity(body.toString(), AlfrescoHttpClient.UTF_8_ENCODING); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, AlfrescoHttpClient.MIME_TYPE_JSON)); post.setEntity(se); HttpClient clientWithAuth = client.getHttpClientWithBasicAuth(userName, password); try { HttpResponse response = clientWithAuth.execute(post); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { if (logger.isTraceEnabled()) { logger.trace("Page " + page.pageId + " was added to site " + siteName); } return true; } else { logger.error("Unable to add page to site " + siteName); return false; } } finally { post.releaseConnection(); client.close(); } }
From source file:org.alfresco.test.util.SiteService.java
/** * Add dashlet to site dashboard/* w w w. j a v a 2 s . c o m*/ * * @param userName String identifier * @param password * @param siteName * @param dashlet * @param layout * @param column * @param position * @return true if the dashlet is added * @throws Exception if error */ public boolean addDashlet(final String userName, final String password, final String siteName, final SiteDashlet dashlet, final DashletLayout layout, final int column, final int position) throws Exception { if (!exists(siteName, userName, password)) { throw new RuntimeException("Site doesn't exists " + siteName); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); String url = client.getAlfrescoUrl() + DashboardCustomization.ADD_DASHLET_URL; org.json.JSONObject body = new org.json.JSONObject(); org.json.JSONArray array = new org.json.JSONArray(); body.put("dashboardPage", "site/" + siteName + "/dashboard"); body.put("templateId", layout.id); Hashtable<String, String> defaultDashlets = new Hashtable<String, String>(); defaultDashlets.put(SiteDashlet.SITE_MEMBERS.id, "component-1-1"); defaultDashlets.put(SiteDashlet.SITE_CONNTENT.id, "component-2-1"); defaultDashlets.put(SiteDashlet.SITE_ACTIVITIES.id, "component-2-2"); Iterator<Map.Entry<String, String>> entries = defaultDashlets.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); org.json.JSONObject jDashlet = new org.json.JSONObject(); jDashlet.put("url", entry.getKey()); jDashlet.put("regionId", entry.getValue()); jDashlet.put("originalRegionId", entry.getValue()); array.put(jDashlet); } org.json.JSONObject newDashlet = new org.json.JSONObject(); newDashlet.put("url", dashlet.id); String region = "component-" + column + "-" + position; newDashlet.put("regionId", region); array.put(newDashlet); body.put("dashlets", array); HttpPost post = new HttpPost(url); StringEntity se = new StringEntity(body.toString(), AlfrescoHttpClient.UTF_8_ENCODING); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, AlfrescoHttpClient.MIME_TYPE_JSON)); post.setEntity(se); HttpClient clientWithAuth = client.getHttpClientWithBasicAuth(userName, password); try { HttpResponse response = clientWithAuth.execute(post); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { if (logger.isTraceEnabled()) { logger.trace("Dashlet " + dashlet.name + " was added to site " + siteName); } return true; } else { logger.error("Unable to add dashlet to site " + siteName); } } finally { post.releaseConnection(); client.close(); } return false; }
From source file:org.alfresco.test.util.UserService.java
/** * Add dashlet to user dashboard//w w w . ja v a2 s. c o m * * @param userName String identifier * @param password * @param dashlet * @param layout * @param column * @param position * @return true if the dashlet is added * @throws Exception if error */ public boolean addDashlet(final String userName, final String password, final UserDashlet dashlet, final DashletLayout layout, final int column, final int position) throws Exception { login(userName, password); AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); String url = client.getAlfrescoUrl() + DashboardCustomization.ADD_DASHLET_URL; org.json.JSONObject body = new org.json.JSONObject(); org.json.JSONArray array = new org.json.JSONArray(); body.put("dashboardPage", "user/" + userName + "/dashboard"); body.put("templateId", layout.id); // keep default dashlets Hashtable<String, String> defaultDashlets = new Hashtable<String, String>(); defaultDashlets.put(UserDashlet.MY_SITES.id, "component-1-1"); defaultDashlets.put(UserDashlet.MY_TASKS.id, "component-1-2"); defaultDashlets.put(UserDashlet.MY_ACTIVITIES.id, "component-2-1"); defaultDashlets.put(UserDashlet.MY_DOCUMENTS.id, "component-2-2"); Iterator<Map.Entry<String, String>> entries = defaultDashlets.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); org.json.JSONObject jDashlet = new org.json.JSONObject(); jDashlet.put("url", entry.getKey()); jDashlet.put("regionId", entry.getValue()); jDashlet.put("originalRegionId", entry.getValue()); array.put(jDashlet); } org.json.JSONObject newDashlet = new org.json.JSONObject(); newDashlet.put("url", dashlet.id); String region = "component-" + column + "-" + position; newDashlet.put("regionId", region); array.put(newDashlet); body.put("dashlets", array); HttpPost post = new HttpPost(url); StringEntity se = new StringEntity(body.toString(), AlfrescoHttpClient.UTF_8_ENCODING); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, AlfrescoHttpClient.MIME_TYPE_JSON)); post.setEntity(se); try { HttpResponse response = client.executeRequest(post); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { if (logger.isTraceEnabled()) { logger.trace("Dashlet " + dashlet.name + " was added on user: " + userName + " dashboard"); } return true; } else { logger.error("Unable to add dashlet to user dashboard " + userName); } } finally { post.releaseConnection(); client.close(); } return false; }
From source file:org.apache.atlas.web.filters.AtlasKnoxSSOAuthenticationFilter.java
private void redirectToKnox(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws IOException, ServletException { if (!isWebUserAgent(httpRequest.getHeader("User-Agent"))) { filterChain.doFilter(httpRequest, httpServletResponse); return;/*from ww w. ja v a2s . c om*/ } String ajaxRequestHeader = httpRequest.getHeader("X-Requested-With"); if ("XMLHttpRequest".equals(ajaxRequestHeader)) { String ssourl = constructLoginURL(httpRequest, true); JSONObject json = new JSONObject(); json.put("knoxssoredirectURL", URLEncoder.encode(ssourl, "UTF-8")); httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, json.toString()); } else { String ssourl = constructLoginURL(httpRequest, false); httpServletResponse.sendRedirect(ssourl); } }
From source file:org.apache.hadoop.chukwa.datacollection.adaptor.sigar.SigarRunner.java
@SuppressWarnings("unchecked") @Override//from w w w . jav a 2 s . c o m public void run() { boolean skip = false; CpuInfo[] cpuinfo = null; CpuPerc[] cpuPerc = null; Mem mem = null; Swap swap = null; FileSystem[] fs = null; String[] netIf = null; Uptime uptime = null; double[] loadavg = null; JSONObject json = new JSONObject(); try { // CPU utilization JSONArray load = new JSONArray(); try { cpuinfo = sigar.getCpuInfoList(); cpuPerc = sigar.getCpuPercList(); JSONArray cpuList = new JSONArray(); for (int i = 0; i < cpuinfo.length; i++) { JSONObject cpuMap = new JSONObject(); cpuMap.putAll(cpuinfo[i].toMap()); cpuMap.put("combined", cpuPerc[i].getCombined() * 100); cpuMap.put("user", cpuPerc[i].getUser() * 100); cpuMap.put("sys", cpuPerc[i].getSys() * 100); cpuMap.put("idle", cpuPerc[i].getIdle() * 100); cpuMap.put("wait", cpuPerc[i].getWait() * 100); cpuMap.put("nice", cpuPerc[i].getNice() * 100); cpuMap.put("irq", cpuPerc[i].getIrq() * 100); cpuList.add(cpuMap); } sigar.getCpuPerc(); json.put("cpu", cpuList); // Uptime uptime = sigar.getUptime(); json.put("uptime", uptime.getUptime()); // Load Average loadavg = sigar.getLoadAverage(); load.add(loadavg[0]); load.add(loadavg[1]); load.add(loadavg[2]); } catch (SigarException se) { log.error("SigarException caused during collection of CPU utilization"); log.error(ExceptionUtils.getStackTrace(se)); } finally { json.put("loadavg", load); } // Memory Utilization JSONObject memMap = new JSONObject(); JSONObject swapMap = new JSONObject(); try { mem = sigar.getMem(); memMap.putAll(mem.toMap()); // Swap Utilization swap = sigar.getSwap(); swapMap.putAll(swap.toMap()); } catch (SigarException se) { log.error("SigarException caused during collection of Memory utilization"); log.error(ExceptionUtils.getStackTrace(se)); } finally { json.put("memory", memMap); json.put("swap", swapMap); } // Network Utilization JSONArray netInterfaces = new JSONArray(); try { netIf = sigar.getNetInterfaceList(); for (int i = 0; i < netIf.length; i++) { NetInterfaceStat net = new NetInterfaceStat(); try { net = sigar.getNetInterfaceStat(netIf[i]); } catch (SigarException e) { // Ignore the exception when trying to stat network interface log.warn("SigarException trying to stat network device " + netIf[i]); continue; } JSONObject netMap = new JSONObject(); netMap.putAll(net.toMap()); if (previousNetworkStats.containsKey(netIf[i])) { JSONObject deltaMap = previousNetworkStats.get(netIf[i]); deltaMap.put("RxBytes", Long.parseLong(netMap.get("RxBytes").toString()) - Long.parseLong(deltaMap.get("RxBytes").toString())); deltaMap.put("RxDropped", Long.parseLong(netMap.get("RxDropped").toString()) - Long.parseLong(deltaMap.get("RxDropped").toString())); deltaMap.put("RxErrors", Long.parseLong(netMap.get("RxErrors").toString()) - Long.parseLong(deltaMap.get("RxErrors").toString())); deltaMap.put("RxPackets", Long.parseLong(netMap.get("RxPackets").toString()) - Long.parseLong(deltaMap.get("RxPackets").toString())); deltaMap.put("TxBytes", Long.parseLong(netMap.get("TxBytes").toString()) - Long.parseLong(deltaMap.get("TxBytes").toString())); deltaMap.put("TxCollisions", Long.parseLong(netMap.get("TxCollisions").toString()) - Long.parseLong(deltaMap.get("TxCollisions").toString())); deltaMap.put("TxErrors", Long.parseLong(netMap.get("TxErrors").toString()) - Long.parseLong(deltaMap.get("TxErrors").toString())); deltaMap.put("TxPackets", Long.parseLong(netMap.get("TxPackets").toString()) - Long.parseLong(deltaMap.get("TxPackets").toString())); netInterfaces.add(deltaMap); skip = false; } else { netInterfaces.add(netMap); skip = true; } previousNetworkStats.put(netIf[i], netMap); } } catch (SigarException se) { log.error("SigarException caused during collection of Network utilization"); log.error(ExceptionUtils.getStackTrace(se)); } finally { json.put("network", netInterfaces); } // Filesystem Utilization JSONArray fsList = new JSONArray(); try { fs = sigar.getFileSystemList(); for (int i = 0; i < fs.length; i++) { FileSystemUsage usage = sigar.getFileSystemUsage(fs[i].getDirName()); JSONObject fsMap = new JSONObject(); fsMap.putAll(fs[i].toMap()); fsMap.put("ReadBytes", usage.getDiskReadBytes()); fsMap.put("Reads", usage.getDiskReads()); fsMap.put("WriteBytes", usage.getDiskWriteBytes()); fsMap.put("Writes", usage.getDiskWrites()); if (previousDiskStats.containsKey(fs[i].getDevName())) { JSONObject deltaMap = previousDiskStats.get(fs[i].getDevName()); deltaMap.put("ReadBytes", usage.getDiskReadBytes() - (Long) deltaMap.get("ReadBytes")); deltaMap.put("Reads", usage.getDiskReads() - (Long) deltaMap.get("Reads")); deltaMap.put("WriteBytes", usage.getDiskWriteBytes() - (Long) deltaMap.get("WriteBytes")); deltaMap.put("Writes", usage.getDiskWrites() - (Long) deltaMap.get("Writes")); deltaMap.put("Total", usage.getTotal()); deltaMap.put("Used", usage.getUsed()); deltaMap.putAll(fs[i].toMap()); fsList.add(deltaMap); skip = false; } else { fsList.add(fsMap); skip = true; } previousDiskStats.put(fs[i].getDevName(), fsMap); } } catch (SigarException se) { log.error("SigarException caused during collection of FileSystem utilization"); log.error(ExceptionUtils.getStackTrace(se)); } finally { json.put("disk", fsList); } json.put("timestamp", System.currentTimeMillis()); byte[] data = json.toString().getBytes(Charset.forName("UTF-8")); sendOffset += data.length; ChunkImpl c = new ChunkImpl("SystemMetrics", "Sigar", sendOffset, data, systemMetrics); if (!skip) { receiver.add(c); } } catch (InterruptedException se) { log.error(ExceptionUtil.getStackTrace(se)); } }
From source file:org.apache.hadoop.chukwa.hicc.Workspace.java
public void changeViewInfo(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); String id = xf.getParameter("name"); String config = request.getParameter("config"); try {//from w w w .ja v a2 s .c o m JSONObject jt = (JSONObject) JSONValue.parse(config); File aFile = new File(path + "/views/" + id + ".view"); String original = getContents(aFile); JSONObject updateObject = (JSONObject) JSONValue.parse(original); updateObject.put("description", jt.get("description")); setContents(path + "/views/" + id + ".view", updateObject.toString()); if (!rename(id, jt.get("description").toString())) { throw new Exception("Rename view file failed"); } File deleteCache = new File(path + "/views/workspace_view_list.cache"); if (!deleteCache.delete()) { log.warn("Can not delete " + path + "/views/workspace_view_list.cache"); } genViewCache(path + "/views"); out.println("Workspace is stored successfully."); } catch (Exception e) { out.println("Workspace store failed."); } }