List of usage examples for org.json XML toJSONObject
public static JSONObject toJSONObject(String string) throws JSONException
From source file:fi.csc.emrex.ncp.JsonController.java
@RequestMapping(value = "/api/elmo", method = RequestMethod.GET) @ResponseBody// ww w . j a v a 2s . c om public String getElmoJSON(@RequestParam(value = "courses", required = false) String[] courses) throws Exception { if (courses != null) { String courseIdList = ""; for (int i = 0; i < courses.length; i++) { courseIdList += courses[i] + ", "; } log.info("Courses: " + courseIdList); } try { ElmoParser parser = (ElmoParser) context.getSession().getAttribute("elmo"); String xmlString; if (courses != null) { log.debug("Courses count: {}", courses.length); List<String> courseList = Arrays.asList(courses); xmlString = parser.getCourseData(courseList); } else { log.debug("Courses count: null"); xmlString = parser.getCourseData(null); } log.trace(xmlString); JSONObject json = XML.toJSONObject(xmlString); return json.toString(); } catch (Exception e) { log.error("Failed to get Elmo JSON", e); StackTraceElement elements[] = e.getStackTrace(); Map<String, Object> error = new HashMap<String, Object>(); Map<String, Object> log = new HashMap<String, Object>(); error.put("message", e.getMessage()); for (int i = 0, n = elements.length; i < n; i++) { log.put(elements[i].getFileName() + " " + elements[i].getLineNumber(), elements[i].getMethodName()); } error.put("stack", log); return new JSONObject(error).toString(); } }
From source file:de.fuberlin.panda.api.jersey.JerseyXmlResource.java
/** * Method for request of XML data via XPath. * /*from w w w. j a va 2s . co m*/ * @return Response XML according to valueExcangeSchema.xsd * @throws WebApplicationException HTTP exception */ @GET @Path("/{XPathExp:.*}") @Produces(MediaType.APPLICATION_JSON) public Response getXmlJSON() throws WebApplicationException { Response response = null; String xmlDoc = new String(); String jsonDoc = new String(); try { if (pandaSettings.getUseClientCaching()) { response = validateClientCache(); if (response != null) { return response; } } DataXmlResource xmlResource = new DataXmlResource(); xmlDoc = xmlResource.getXml(uriInfo, pandaSettings); JSONObject json = XML.toJSONObject(xmlDoc); //JSON String with pretty printing jsonDoc = json.toString(4); // Throw 404 WebApplicationException if no values found if (jsonDoc.isEmpty()) { throw new WebApplicationException(404); } } catch (WebApplicationException e) { throw e; } catch (Exception e) { logger.warning(e.getMessage() + "\n" + uriInfo.getAbsolutePath().getPath()); throw new WebApplicationException(404); } response = Response.ok(jsonDoc, MediaType.APPLICATION_JSON).tag(this.eTag).build(); return response; }
From source file:org.opencastproject.workflow.handler.mediapackagepost.MediaPackagePostOperationHandler.java
/** * {@inheritDoc}/* w w w . j a v a 2 s.c o m*/ * * @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance, * JobContext) */ public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException { // get configuration WorkflowOperationInstance currentOperation = workflowInstance.getCurrentOperation(); Configuration config = new Configuration(currentOperation); MediaPackage mp = workflowInstance.getMediaPackage(); /* Check if we need to replace the Mediapackage we got with the published * Mediapackage from the Search Service */ if (config.mpFromSearch) { SearchQuery searchQuery = new SearchQuery(); searchQuery.withId(mp.getIdentifier().toString()); SearchResult result = searchService.getByQuery(searchQuery); if (result.size() != 1) { throw new WorkflowOperationException("Received multiple results for identifier" + "\"" + mp.getIdentifier().toString() + "\" from search service. "); } logger.info("Getting Mediapackage from Search Service"); mp = result.getItems()[0].getMediaPackage(); } try { logger.info("Submitting \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") as " + config.getFormat().name() + " to " + config.getUrl().toString()); // serialize MediaPackage to target format OutputStream serOut = new ByteArrayOutputStream(); MediaPackageParser.getAsXml(mp, serOut, false); String mpStr = serOut.toString(); serOut.close(); if (config.getFormat() == Configuration.Format.JSON) { JSONObject json = XML.toJSONObject(mpStr); mpStr = json.toString(); if (mpStr.startsWith("{\"ns2:")) { mpStr = (new StringBuilder()).append("{\"").append(mpStr.substring(6)).toString(); } } // Log mediapackge if (config.debug()) { logger.info(mpStr); } // constrcut message body List<NameValuePair> data = new ArrayList<NameValuePair>(); data.add(new BasicNameValuePair("mediapackage", mpStr)); data.addAll(config.getAdditionalFields()); // construct POST HttpPost post = new HttpPost(config.getUrl()); post.setEntity(new UrlEncodedFormEntity(data, config.getEncoding())); // execute POST DefaultHttpClient client = new DefaultHttpClient(); // Handle authentication if (config.authenticate()) { URL targetUrl = config.getUrl().toURL(); client.getCredentialsProvider().setCredentials( new AuthScope(targetUrl.getHost(), targetUrl.getPort()), config.getCredentials()); } HttpResponse response = client.execute(post); // throw Exception if target host did not return 200 int status = response.getStatusLine().getStatusCode(); if (status == 200) { if (config.debug()) { logger.info("Successfully submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") to " + config.getUrl().toString() + ": 200 OK"); } } else if (status == 418) { logger.warn("Submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") to " + config.getUrl().toString() + ": The target claims to be a teapot. " + "The Reason for this is probably an insane programmer."); } else { throw new WorkflowOperationException( "Faild to submit \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + "), " + config.getUrl().toString() + " answered with: " + Integer.toString(status)); } } catch (Exception e) { if (e instanceof WorkflowOperationException) { throw (WorkflowOperationException) e; } else { throw new WorkflowOperationException(e); } } return createResult(mp, Action.CONTINUE); }
From source file:org.opencastproject.workflow.handler.mediapackagepost.MediaPackagePostOperationHandler.java
/** Serialize XML Document to JSON string * * @param doc/*from ww w .j a va2 s .c om*/ * @return * @throws Exception */ private String xmlToJSONString(Document doc) throws Exception { JSONObject json = XML.toJSONObject(xmlToString(doc)); return json.toString(); }