/** * Parses AGGREGATE results for Oskari front * * @param response WPS vec:aggregate execute results * @param analysisLayer analysis layer params (field/columns info) * @return JSON.toSting() eg. aggregate WPS results * ********************************************************************** */ public String parseAggregateResults(String response, AnalysisLayer analysisLayer) { try { // convert xml/text String to JSON final JSONObject json = XML.toJSONObject(response); // all // Add field name final AggregateMethodParams aggreParams = (AggregateMethodParams) analysisLayer.getAnalysisMethodParams(); String fieldName = aggreParams.getAggreField1(); if (analysisLayer.getInputAnalysisId() != null) { fieldName = analysisDataService.SwitchField2OriginalField( fieldName, analysisLayer.getInputAnalysisId()); } json.put("fieldName", fieldName); return json.toString(); } catch (JSONException e) { log.error(e, "XML to JSON failed", response); } return "{}"; }
public static HashMap<String, Integer> getAnimeSearchedMAL( String username, String password, String anime) { HashMap<String, Integer> map = new HashMap<String, Integer>(); JSONObject xmlJSONObj; String json = ""; String xml = ""; try { xml = searchAnimeMAL(username, password, anime); xmlJSONObj = XML.toJSONObject(xml); json = xmlJSONObj.toString(4); } catch (Exception e) { MAMUtil.writeLog(e); e.printStackTrace(); } JsonParser parser = new JsonParser(); JsonObject root = parser.parse(json).getAsJsonObject(); if (root.has("anime") && root.get("anime").getAsJsonObject().get("entry").isJsonArray()) { JsonArray searchedAnime = root.get("anime").getAsJsonObject().get("entry").getAsJsonArray(); for (JsonElement obj : searchedAnime) { String name = obj.getAsJsonObject().get("title").getAsString(); int id = obj.getAsJsonObject().get("id").getAsInt(); map.put(name, id); } } else if (root.has("anime")) { JsonObject obj = root.get("anime").getAsJsonObject().get("entry").getAsJsonObject(); int id = obj.getAsJsonObject().get("id").getAsInt(); map.put(anime, id); } return map; }
/** * This method <code>onlinePayment</code> is used for the Both M-pesa & Tigo-pesa PaymentGateways * to Pay the Money. * * @param requestData Containg input data in the Form of Xml/Soap . * @return */ @POST @Consumes({MediaType.WILDCARD}) @Produces({MediaType.APPLICATION_XML}) public String onlinePayment(final String requestData) { try { final JSONObject xmlJSONObj = XML.toJSONObject(requestData); jsonData = this.returnJsonFromXml(xmlJSONObj); final CommandWrapper commandRequest = new CommandWrapperBuilder().createPaymentGateway().withJson(jsonData.toString()).build(); result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); success = "SUCCESS"; errorDesc = ""; errorCode = Long.valueOf(0); contentData = "OBSTRANSACTIONID=" + result.resourceId(); return this.returnToServer(); } catch (ReceiptNoDuplicateException e) { success = "DUPLICATE_TXN"; errorDesc = "DUPLICATE"; errorCode = Long.valueOf(1); contentData = "TXNID ALREADY EXIST"; return this.returnToServer(); } catch (JSONException e) { return e.getCause().toString(); } catch (PlatformDataIntegrityException e) { return null; } }
protected void SaveDirectory(Document doc) throws TransformerException, ParserConfigurationException { String xmlStr = OperateXMLByDOM.doc2FormatString(doc); AsciiSaveUtil.saveAscii(outDir+"tree.xml", xmlStr); // hack的方法, 给每个目录加一个空节点 List<Node> nl2 = new ArrayList<Node>(); nl2.add(doc.getElementsByTagName("root").item(0)); NodeList nl = doc.getElementsByTagName("children"); for (int i = 0; i < nl.getLength(); i++) { if (((Element)nl.item(i)).getAttribute("id") == "") nl2.add(nl.item(i)); } for (Node node: nl2){ node.appendChild(doc.createElement("children")); } xmlStr = OperateXMLByDOM.doc2FormatString(doc); JSONObject soapDatainJsonObject = XML.toJSONObject(xmlStr); String jsonString = soapDatainJsonObject.toString(); // 通过字符替换把这些空节点去掉,以达到产生[]括号对的目的 String tmp = jsonString.replaceAll(",\\\"\\\"", ""); String json = "["+tmp.substring(8, tmp.length()-1)+"]"; AsciiSaveUtil.saveAscii(outDir+"tree.json", json); }
public void LoadSeedData(String strColl, String metadatafile) throws Exception { try { InputStream is = this.getClass().getResourceAsStream(metadatafile); String xml; xml = IOUtils.toString(is); JSONObject rwSeed = XML.toJSONObject(xml); if (!rwSeed.isNull("ReferralWireSeedData")) { JSONObject json = rwSeed.getJSONObject("ReferralWireSeedData"); DBCollection dbcoll = store.getColl(strColl); Object coll = (Object) json.get(strColl); if (coll instanceof JSONArray) { JSONArray defs = (JSONArray) coll; for (int i = 0; i < defs.length(); i++) { Object obj = (JSONObject) defs.get(i); dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(obj.toString())); } } else { dbcoll.insert((DBObject) com.mongodb.util.JSON.parse(coll.toString())); } } } catch (IOException e) { // TODO Auto-generated catch block log.debug("API Error: ", e); } }
public void writeSonarResults() { int page = 1; int total = 1; JSONArray issues = new JSONArray(); JSONObject json = null; try { while (issues.length() < total) { json = new JSONObject(getSonarResults("http://localhost:9000", page)); total = (int) json.get("total"); JSONArray issueSubset = json.getJSONArray("issues"); for (int i = 0; i < issueSubset.length(); i++) { issues.put(issueSubset.get(i)); } page++; } json.put("issues", issues); String xml = XML.toString(json); java.io.FileWriter fw = new java.io.FileWriter(SONAR_FILE); fw.write(xml); fw.close(); } catch (Exception e) { System.out.println("There was an error while writing SonarQube results."); } }
/** * Parses an XML config file. * * @param filename The path to the file to parse. */ public void parse(String filename) throws ConfigException { try { String xml = Utils.fileToString(filename); JSONObject jobj = XML.toJSONObject(xml); configObject = (Map) new JSONReader(jobj.toString()).readObject(); } catch (Exception e) { throw new ConfigException("Error parsing config", e); } }
/* */ private static void stringify(JSONArray ja, StringBuffer b) /* */ throws JSONException /* */ { /* 243 */ b.append('<'); /* 244 */ b.append(ja.get(0)); /* 245 */ Object o = ja.opt(1); /* */ int i; /* */ int i; /* 246 */ if ((o instanceof JSONObject)) /* */ { /* 250 */ JSONObject jo = (JSONObject) o; /* 251 */ Iterator keys = jo.keys(); /* 252 */ while (keys.hasNext()) { /* 253 */ String k = keys.next().toString(); /* 254 */ Object v = jo.get(k).toString(); /* 255 */ b.append(' '); /* 256 */ b.append(k); /* 257 */ b.append("=\""); /* 258 */ b.append(XML.escape((String) v)); /* 259 */ b.append('"'); /* */ } /* 261 */ i = 2; /* */ } else { /* 263 */ i = 1; /* */ } /* 265 */ int len = ja.length(); /* */ /* 267 */ if (i >= len) { /* 268 */ b.append("/>"); /* */ } else { /* 270 */ b.append('>'); /* 271 */ while (i < len) { /* 272 */ Object v = ja.get(i); /* 273 */ if ((v instanceof JSONArray)) /* 274 */ stringify((JSONArray) v, b); /* */ else { /* 276 */ b.append(XML.escape(v.toString())); /* */ } /* 278 */ i++; /* */ } /* 280 */ b.append("</"); /* 281 */ b.append(ja.get(0)); /* 282 */ b.append('>'); /* */ } /* */ }
public static byte[] convertToJSON( IExtensionHelpers helpers, IHttpRequestResponse requestResponse) { byte[] request = requestResponse.getRequest(); if (Objects.equals(helpers.analyzeRequest(request).getMethod(), "GET")) { request = helpers.toggleRequestMethod(request); } IRequestInfo requestInfo = helpers.analyzeRequest(request); int bodyOffset = requestInfo.getBodyOffset(); byte content_type = requestInfo.getContentType(); String body = new String(request, bodyOffset, request.length - bodyOffset); String json = ""; Boolean success = true; try { if (content_type == 3) { JSONObject xmlJSONObject = XML.toJSONObject(body); json = xmlJSONObject.toString(2); } else if (content_type == 0 || content_type == 1) { Map<String, String> params = splitQuery(body); Gson gson = new Gson(); json = gson.toJson(params); } else { json = body; } } catch (Exception e) { success = false; } if (!success) { return request; } else { List<String> headers; headers = helpers.analyzeRequest(request).getHeaders(); Iterator<String> iter = headers.iterator(); while (iter.hasNext()) { if (iter.next().contains("Content-Type")) iter.remove(); } headers.add("Content-Type: application/json;charset=UTF-8"); return helpers.buildHttpMessage(headers, json.getBytes()); } }
private void sendResponse(HttpServletResponse resp, String payload, boolean json) { if (json) { JSONObject jsonObject = XML.toJSONObject(payload); payload = jsonObject.toString(3); } try { OutputStream outputStream = resp.getOutputStream(); outputStream.write(payload.getBytes()); outputStream.flush(); } catch (IOException e) { throw new HTTPException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
// Send the response payload to the client. private void sendResponse(HttpServletResponse response, String payload, boolean json) { try { // Convert to JSON? if (json) { JSONObject jobt = XML.toJSONObject(payload); payload = jobt.toString(3); // 3 is indentation level for nice // look } OutputStream out = response.getOutputStream(); out.write(payload.getBytes()); out.flush(); } catch (Exception exception) { throw new HTTPException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
public XMLImport(File xmlFile, String worksheetName, Workspace workspace) { super(worksheetName, workspace); try { String fileContents = FileUtil.readFileContentsToString(xmlFile); // Converting the XML to JSON JSONObject json = XML.toJSONObject(fileContents); jsonImport = new JsonImport(json, this.getFactory(), this.getWorksheet()); } catch (JSONException ex) { logger.error("Error in populating the worksheet with XML"); } catch (IOException ex) { logger.error("Error in reading the XML file"); } }
public void LoadSTNSpeakers(String mapfile) throws Exception { String mongoTableName = "rwParty"; String xmlCollection = "SeedLOVMaps"; try { InputStream is = this.getClass().getResourceAsStream(mapfile); String xml; xml = IOUtils.toString(is); JSONObject rwSeed = XML.toJSONObject(xml); if (!rwSeed.isNull(xmlCollection)) { JSONObject json = rwSeed.getJSONObject(xmlCollection); DBCollection dbTable = store.getColl(mongoTableName); Object xmlRecords = (Object) json.get(mongoTableName); if (xmlRecords instanceof JSONArray == false) { JSONObject xmlRecord = (JSONObject) xmlRecords; JSONArray jAry = new JSONArray(); jAry.put(xmlRecord); xmlRecords = jAry; } if (xmlRecords instanceof JSONArray) { JSONArray xmlRecordAry = (JSONArray) xmlRecords; for (int i = 0; i < xmlRecordAry.length(); i++) { JSONObject xmlRecord = (JSONObject) xmlRecordAry.get(i); String parent_GlobalVal = xmlRecord.getString("parent_GlobalVal"); String child_GlobalVal = xmlRecord.getString("child_GlobalVal"); String parent_LovType = xmlRecord.getString("parent_LovType"); String child_LovType = xmlRecord.getString("child_LovType"); String childId = getLOVId(child_LovType, child_GlobalVal); String parentId = getLOVId(parent_LovType, parent_GlobalVal); xmlRecord.put("parentId", parentId); xmlRecord.put("childId", childId); dbTable.insert((DBObject) com.mongodb.util.JSON.parse(xmlRecord.toString())); } } else { dbTable.insert((DBObject) com.mongodb.util.JSON.parse(xmlRecords.toString())); } } } catch (IOException e) { // TODO Auto-generated catch block log.debug("API Error: ", e); } }
/** * Marshals a SearchResult or ModsType object to an XML string. This string is converted to json * using the org.json package. Order of the json array is not guaranteed (as per spec); TO DO * (201405007) - investigate means for preserving XML order (json schema?) * * @param obj a a SearchResult or ModsType object for conversion to json string * @return the json String */ protected String writeJson(Object obj) throws JAXBException { StringWriter sw = new StringWriter(); String jsonString = null; Marshaller jaxbMarshaller = JAXBHelper.context.createMarshaller(); jaxbMarshaller.marshal(obj, sw); try { String xml = sw.toString(); JSONObject xmlJSONObj = XML.toJSONObject(xml); jsonString = xmlJSONObj.toString(5); // System.out.println(jsonString); } catch (JSONException je) { log.error(je.getMessage()); je.printStackTrace(); } return jsonString; }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); String location = URLDecoder.decode(request.getParameter("location")); String type = URLDecoder.decode(request.getParameter("type")); String unit = URLDecoder.decode(request.getParameter("unit")); String awsURL = "http://default-environment-ii9naedwp8.elasticbeanstalk.com/?location=" + URLEncoder.encode(location) + "&type=" + type + "&unit=" + unit; // out.write(awsURL); String myurl = URLEncoder.encode(awsURL); // out.write("\n"+myurl); URL url = new URL(awsURL); URLConnection urlConnection = url.openConnection(); InputStream awsResponse = urlConnection.getInputStream(); InputStreamReader iSReader = new InputStreamReader(awsResponse); StringBuffer sb = new StringBuffer(); String xmlLine; BufferedReader buf = new BufferedReader(iSReader); try { while ((xmlLine = buf.readLine()) != null) { sb.append(xmlLine); } } catch (IOException ex) { ex.printStackTrace(); } xmlLine = sb.toString(); response.setContentType("application/json; charset=UTF-8"); int indent = 6; try { JSONObject jsonObj = XML.toJSONObject(xmlLine); String json1 = jsonObj.toString(indent); out.write(json1); } catch (JSONException ex) { ex.printStackTrace(); } }
public void LoadSavedSearch(String datafile, String mongoTableName, String xmlCollection) throws Exception { // String mongoTableName = "rwSavedSearch"; // String xmlCollection = "SavedSearches"; try { InputStream is = this.getClass().getResourceAsStream(datafile); String xml; xml = IOUtils.toString(is); JSONObject rwSeed = XML.toJSONObject(xml); if (!rwSeed.isNull(xmlCollection)) { JSONObject json = rwSeed.getJSONObject(xmlCollection); DBCollection dbTable = store.getColl(mongoTableName); Object xmlRecords = (Object) json.get(mongoTableName); if (xmlRecords instanceof JSONArray == false) { JSONObject xmlRecord = (JSONObject) xmlRecords; JSONArray jAry = new JSONArray(); jAry.put(xmlRecord); xmlRecords = jAry; } if (xmlRecords instanceof JSONArray) { JSONArray xmlRecordAry = (JSONArray) xmlRecords; for (int i = 0; i < xmlRecordAry.length(); i++) { JSONObject xmlRecord = (JSONObject) xmlRecordAry.get(i); dbTable.insert((DBObject) com.mongodb.util.JSON.parse(xmlRecord.toString())); } } else { dbTable.insert((DBObject) com.mongodb.util.JSON.parse(xmlRecords.toString())); } } } catch (IOException e) { // TODO Auto-generated catch block log.debug("API Error: ", e); } }
private DocumentPojo buildDocument( SyndEntry entry, SourcePojo source, LinkedList<String> duplicateSources) { String tmpURL = this.cleanUrlStart(entry.getLink().toString()); // (can't return null because called from code which checks this) // create the feed pojo DocumentPojo doc = new DocumentPojo(); doc.setUrl(tmpURL); doc.setCreated(new Date()); doc.setModified(new Date()); // Strip out html if it is present if (entry.getTitle() != null) doc.setTitle(entry.getTitle().replaceAll("\\<.*?\\>", "").trim()); if (entry.getDescription() != null) doc.setDescription(entry.getDescription().getValue().replaceAll("\\<.*?\\>", "").trim()); if (entry.getPublishedDate() != null) { doc.setPublishedDate(entry.getPublishedDate()); } else { doc.setPublishedDate(new Date()); } // Clone from an existing source if we can: if (!duplicateSources.isEmpty() && (null == doc.getUpdateId())) { // (can't duplicate updating document) doc.setDuplicateFrom(duplicateSources.getFirst()); } // GeoRSS GeoRSSModule geoRSSModule = GeoRSSUtils.getGeoRSS(entry); // currently does not handle <georss:circle> if (null != geoRSSModule) { if (null != geoRSSModule.getPosition()) { double lat = geoRSSModule.getPosition().getLatitude(); double lon = geoRSSModule.getPosition().getLongitude(); GeoPojo gp = new GeoPojo(); gp.lat = lat; gp.lon = lon; doc.setDocGeo(gp); } if (null != geoRSSModule.getGeometry()) { AbstractGeometry ag = geoRSSModule.getGeometry(); if (ag.getClass().equals(new LineString().getClass())) { // <georss:line> LineString ls = ((LineString) geoRSSModule.getGeometry()); double latAvg = 0.0; double lonAvg = 0.0; int length = ls.getPositionList().size(); for (int i = 0; i < length; i++) { latAvg += ls.getPositionList().getLatitude(i); lonAvg += ls.getPositionList().getLongitude(i); } latAvg = latAvg / length; lonAvg = lonAvg / length; GeoPojo gp = new GeoPojo(); gp.lat = latAvg; gp.lon = lonAvg; doc.setDocGeo(gp); } else if (ag.getClass().equals(new Polygon().getClass())) // <georss:polygon> { Polygon poly = ((Polygon) geoRSSModule.getGeometry()); AbstractRing ar = poly.getExterior(); LinearRing lr = (LinearRing) ar; double latAvg = 0.0; double lonAvg = 0.0; int length = lr.getPositionList().size(); for (int i = 0; i < length; i++) { latAvg += lr.getPositionList().getLatitude(i); lonAvg += lr.getPositionList().getLongitude(i); } latAvg = latAvg / length; lonAvg = lonAvg / length; GeoPojo gp = new GeoPojo(); gp.lat = latAvg; gp.lon = lonAvg; doc.setDocGeo(gp); } else if (ag.getClass().equals(new Envelope().getClass())) { // <georss:box> Envelope env = ((Envelope) geoRSSModule.getGeometry()); double latAvg = (env.getMaxLatitude() + env.getMinLatitude()) / 2; double lonAvg = (env.getMaxLongitude() + env.getMinLongitude()) / 2; GeoPojo gp = new GeoPojo(); gp.lat = latAvg; gp.lon = lonAvg; doc.setDocGeo(gp); } } } // end if GeoRSS // Arbitrary other metadata: if (null != entry.getForeignMarkup()) { JSONObject rssMetadata = new JSONObject(); @SuppressWarnings("unchecked") List<Element> fms = (List<Element>) entry.getForeignMarkup(); for (Element fm : fms) { try { JSONObject subObj = XML.toJSONObject(new XMLOutputter().outputString(fm)); if (1 == subObj.length()) { for (String name : JSONObject.getNames(subObj)) { rssMetadata.put(name, subObj.get(name)); } } else { // (this will never happen in practice?) rssMetadata.put(fm.getName(), subObj); } } catch (JSONException e) { } // (do nothing just carry on) } if (!fms.isEmpty()) { doc.addToMetadata( "_FEED_METADATA_", XmlToMetadataParser.convertJsonObjectToLinkedHashMap(rssMetadata)); } } // TESTED (longs converted to string, eg edgar:assistantDirector from // "http.www.sec.gov.archives.edgar.usgaap.rss.xml") return doc; }
public static byte[] convertToXML(IExtensionHelpers helpers, IHttpRequestResponse requestResponse) throws Exception { byte[] request = requestResponse.getRequest(); if (Objects.equals(helpers.analyzeRequest(request).getMethod(), "GET")) { request = helpers.toggleRequestMethod(request); } IRequestInfo requestInfo = helpers.analyzeRequest(request); int bodyOffset = requestInfo.getBodyOffset(); byte content_type = requestInfo.getContentType(); String body = new String(request, bodyOffset, request.length - bodyOffset, "UTF-8"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc = new Document() { public String getNodeName() { return null; } public String getNodeValue() throws DOMException { return null; } public void setNodeValue(String nodeValue) throws DOMException {} public short getNodeType() { return 0; } public Node getParentNode() { return null; } public NodeList getChildNodes() { return null; } public Node getFirstChild() { return null; } public Node getLastChild() { return null; } public Node getPreviousSibling() { return null; } public Node getNextSibling() { return null; } public NamedNodeMap getAttributes() { return null; } public Document getOwnerDocument() { return null; } public Node insertBefore(Node newChild, Node refChild) throws DOMException { return null; } public Node replaceChild(Node newChild, Node oldChild) throws DOMException { return null; } public Node removeChild(Node oldChild) throws DOMException { return null; } public Node appendChild(Node newChild) throws DOMException { return null; } public boolean hasChildNodes() { return false; } public Node cloneNode(boolean deep) { return null; } public void normalize() {} public boolean isSupported(String feature, String version) { return false; } public String getNamespaceURI() { return null; } public String getPrefix() { return null; } public void setPrefix(String prefix) throws DOMException {} public String getLocalName() { return null; } public boolean hasAttributes() { return false; } public String getBaseURI() { return null; } public short compareDocumentPosition(Node other) throws DOMException { return 0; } public String getTextContent() throws DOMException { return null; } public void setTextContent(String textContent) throws DOMException {} public boolean isSameNode(Node other) { return false; } public String lookupPrefix(String namespaceURI) { return null; } public boolean isDefaultNamespace(String namespaceURI) { return false; } public String lookupNamespaceURI(String prefix) { return null; } public boolean isEqualNode(Node arg) { return false; } public Object getFeature(String feature, String version) { return null; } public Object setUserData(String key, Object data, UserDataHandler handler) { return null; } public Object getUserData(String key) { return null; } public DocumentType getDoctype() { return null; } public DOMImplementation getImplementation() { return null; } public Element getDocumentElement() { return null; } public Element createElement(String tagName) throws DOMException { return null; } public DocumentFragment createDocumentFragment() { return null; } public Text createTextNode(String data) { return null; } public Comment createComment(String data) { return null; } public CDATASection createCDATASection(String data) throws DOMException { return null; } public ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException { return null; } public Attr createAttribute(String name) throws DOMException { return null; } public EntityReference createEntityReference(String name) throws DOMException { return null; } public NodeList getElementsByTagName(String tagname) { return null; } public Node importNode(Node importedNode, boolean deep) throws DOMException { return null; } public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException { return null; } public Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException { return null; } public NodeList getElementsByTagNameNS(String namespaceURI, String localName) { return null; } public Element getElementById(String elementId) { return null; } public String getInputEncoding() { return null; } public String getXmlEncoding() { return null; } public boolean getXmlStandalone() { return false; } public void setXmlStandalone(boolean xmlStandalone) throws DOMException {} public String getXmlVersion() { return null; } public void setXmlVersion(String xmlVersion) throws DOMException {} public boolean getStrictErrorChecking() { return false; } public void setStrictErrorChecking(boolean strictErrorChecking) {} public String getDocumentURI() { return null; } public void setDocumentURI(String documentURI) {} public Node adoptNode(Node source) throws DOMException { return null; } public DOMConfiguration getDomConfig() { return null; } public void normalizeDocument() {} public Node renameNode(Node n, String namespaceURI, String qualifiedName) throws DOMException { return null; } }; StringBuilder xml = new StringBuilder(); xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); xml.append("<root>"); if (content_type == 0 || content_type == 1) { Map<String, String> params = splitQuery(body); Gson gson = new Gson(); body = gson.toJson(params); } Boolean success = true; try { JSONObject json = new JSONObject(body); xml.append(XML.toString(json)); xml.append("</root>"); DocumentBuilder builder = factory.newDocumentBuilder(); ByteArrayInputStream input = new ByteArrayInputStream(xml.toString().getBytes("UTF-8")); doc = builder.parse(input); } catch (Exception e) { success = false; } if (!success) { return null; } else { List<String> headers; headers = helpers.analyzeRequest(request).getHeaders(); Iterator<String> iter = headers.iterator(); while (iter.hasNext()) { if (iter.next().contains("Content-Type")) iter.remove(); } headers.add("Content-Type: application/xml;charset=UTF-8"); return helpers.buildHttpMessage(headers, prettyPrint(doc).getBytes()); } }
/** * Parse XML values and store them in a JSONArray. * * @param x The XMLTokener containing the source string. * @param arrayForm true if array form, false if object form. * @param ja The JSONArray that is containing the current tag or null if we are at the outermost * level. * @param keepStrings Don't type-convert text nodes and attibute values * @return A JSONArray if the value is the outermost tag, otherwise null. * @throws JSONException */ private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja, boolean keepStrings) throws JSONException { String attribute; char c; String closeTag = null; int i; JSONArray newja = null; JSONObject newjo = null; Object token; String tagName = null; // Test for and skip past these forms: // <!-- ... --> // <![ ... ]]> // <! ... > // <? ... ?> while (true) { if (!x.more()) { throw x.syntaxError("Bad XML"); } token = x.nextContent(); if (token == XML.LT) { token = x.nextToken(); if (token instanceof Character) { if (token == XML.SLASH) { // Close tag </ token = x.nextToken(); if (!(token instanceof String)) { throw new JSONException("Expected a closing name instead of '" + token + "'."); } if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped close tag"); } return token; } else if (token == XML.BANG) { // <! c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); } else { x.back(); } } else if (c == '[') { token = x.nextToken(); if (token.equals("CDATA") && x.next() == '[') { if (ja != null) { ja.put(x.nextCDATA()); } } else { throw x.syntaxError("Expected 'CDATA['"); } } else { i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == XML.LT) { i += 1; } else if (token == XML.GT) { i -= 1; } } while (i > 0); } } else if (token == XML.QUEST) { // <? x.skipPast("?>"); } else { throw x.syntaxError("Misshaped tag"); } // Open tag < } else { if (!(token instanceof String)) { throw x.syntaxError("Bad tagName '" + token + "'."); } tagName = (String) token; newja = new JSONArray(); newjo = new JSONObject(); if (arrayForm) { newja.put(tagName); if (ja != null) { ja.put(newja); } } else { newjo.put("tagName", tagName); if (ja != null) { ja.put(newjo); } } token = null; for (; ; ) { if (token == null) { token = x.nextToken(); } if (token == null) { throw x.syntaxError("Misshaped tag"); } if (!(token instanceof String)) { break; } // attribute = value attribute = (String) token; if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { throw x.syntaxError("Reserved attribute."); } token = x.nextToken(); if (token == XML.EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } newjo.accumulate(attribute, keepStrings ? token : XML.stringToValue((String) token)); token = null; } else { newjo.accumulate(attribute, ""); } } if (arrayForm && newjo.length() > 0) { newja.put(newjo); } // Empty tag <.../> if (token == XML.SLASH) { if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped tag"); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } // Content, between <...> and </...> } else { if (token != XML.GT) { throw x.syntaxError("Misshaped tag"); } closeTag = (String) parse(x, arrayForm, newja, keepStrings); if (closeTag != null) { if (!closeTag.equals(tagName)) { throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); } tagName = null; if (!arrayForm && newja.length() > 0) { newjo.put("childNodes", newja); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } } } } } else { if (ja != null) { ja.put( token instanceof String ? keepStrings ? token : XML.stringToValue((String) token) : token); } } } }
/** * Reverse the JSONML transformation, making an XML text from a JSONObject. The JSONObject must * contain a "tagName" property. If it has children, then it must have a "childNodes" property * containing an array of objects. The other properties are attributes with string values. * * @param jo A JSONObject. * @return An XML string. * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { StringBuilder sb = new StringBuilder(); int i; JSONArray ja; String key; Iterator<String> keys; int length; Object object; String tagName; String value; // Emit <tagName tagName = jo.optString("tagName"); if (tagName == null) { return XML.escape(jo.toString()); } XML.noSpace(tagName); tagName = XML.escape(tagName); sb.append('<'); sb.append(tagName); // Emit the attributes keys = jo.keys(); while (keys.hasNext()) { key = keys.next(); if (!"tagName".equals(key) && !"childNodes".equals(key)) { XML.noSpace(key); value = jo.optString(key); if (value != null) { sb.append(' '); sb.append(XML.escape(key)); sb.append('='); sb.append('"'); sb.append(XML.escape(value)); sb.append('"'); } } } // Emit content in body ja = jo.optJSONArray("childNodes"); if (ja == null) { sb.append('/'); sb.append('>'); } else { sb.append('>'); length = ja.length(); for (i = 0; i < length; i += 1) { object = ja.get(i); if (object != null) { if (object instanceof String) { sb.append(XML.escape(object.toString())); } else if (object instanceof JSONObject) { sb.append(toString((JSONObject) object)); } else if (object instanceof JSONArray) { sb.append(toString((JSONArray) object)); } else { sb.append(object.toString()); } } } sb.append('<'); sb.append('/'); sb.append(tagName); sb.append('>'); } return sb.toString(); }
/** * Reverse the JSONML transformation, making an XML text from a JSONArray. * * @param ja A JSONArray. * @return An XML string. * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { int i; JSONObject jo; String key; Iterator<String> keys; int length; Object object; StringBuilder sb = new StringBuilder(); String tagName; String value; // Emit <tagName tagName = ja.getString(0); XML.noSpace(tagName); tagName = XML.escape(tagName); sb.append('<'); sb.append(tagName); object = ja.opt(1); if (object instanceof JSONObject) { i = 2; jo = (JSONObject) object; // Emit the attributes keys = jo.keys(); while (keys.hasNext()) { key = keys.next(); XML.noSpace(key); value = jo.optString(key); if (value != null) { sb.append(' '); sb.append(XML.escape(key)); sb.append('='); sb.append('"'); sb.append(XML.escape(value)); sb.append('"'); } } } else { i = 1; } // Emit content in body length = ja.length(); if (i >= length) { sb.append('/'); sb.append('>'); } else { sb.append('>'); do { object = ja.get(i); i += 1; if (object != null) { if (object instanceof String) { sb.append(XML.escape(object.toString())); } else if (object instanceof JSONObject) { sb.append(toString((JSONObject) object)); } else if (object instanceof JSONArray) { sb.append(toString((JSONArray) object)); } } } while (i < length); sb.append('<'); sb.append('/'); sb.append(tagName); sb.append('>'); } return sb.toString(); }
private JSONObject convertXMLToJSON(String xmlData) throws JSONException, JAXBException { // Unmarshall the xml into a GraphML ByteArrayInputStream baiStream = new ByteArrayInputStream(xmlData.getBytes()); JAXBContext jc = JAXBContext.newInstance(GraphMLUtil.GRAPHML_CLASSES); Unmarshaller unmarshaller = jc.createUnmarshaller(); GraphML graphML = (GraphML) unmarshaller.unmarshal(baiStream); // eventually check version for compatibility s_logger.info("Importing chart version: {}", graphML.getversion()); Graph graph = graphML.getGraph(); JSONObject toReturn = new JSONObject(), miscData = null, columnJSON, nodeJSON = null, clusterJSON; String cachedClusterJSON = null; int columnIdx = -1, rowIdx = -1; List<List<JSONObject>> allColumns = new ArrayList<List<JSONObject>>(); List<JSONObject> currColumn, outColumns = new ArrayList<JSONObject>(); // first, set up the column and misc JSON data contained in the graph for (GraphDataXML data : graph.getdata()) { if (data.getkey().startsWith("column")) { columnJSON = XML.toJSONObject(data.getvalue()); columnIdx = Integer.parseInt(data.getkey().substring(6)); while (columnIdx >= outColumns.size()) { outColumns.add(new JSONObject()); } outColumns.set(columnIdx, columnJSON); allColumns.add(new ArrayList<JSONObject>()); } else if (data.getkey().equals("miscData")) { miscData = XML.toJSONObject(data.getvalue()); } } // next, iterate through the graph nodes and place the JSONObject for each into it's proper // row/column for (GraphNode node : graph.getnode()) { for (GraphData data : node.getdata()) { // parse the goodies from each file node if (data.getkey().equals("column")) { columnIdx = Integer.parseInt(data.getvalue()); } else if (data.getkey().equals("row")) { rowIdx = Integer.parseInt(data.getvalue()); } } for (GraphDataXML data : node.getnodedata()) { // parse the goodies from each data node if (data.getkey().equals("fileJSON")) { nodeJSON = XML.toJSONObject(data.getvalue()); } else if (data.getkey().equals("clusterJSON")) { cachedClusterJSON = data.getvalue(); } } if (nodeJSON != null && nodeJSON.has("clusterUIObject") && !nodeJSON.get("clusterUIObject").toString().equals("null")) { clusterJSON = nodeJSON.getJSONObject("clusterUIObject"); // do annoying cleanup insertJSONArray(clusterJSON, "children"); insertJSONArray(clusterJSON.getJSONObject("spec"), "members"); } if (cachedClusterJSON != null) { PermitSet permits = new PermitSet(); try { List<String> entityIds = new LinkedList<String>(); List<FL_Cluster> allClusters = ClusterHelper.listFromJson(cachedClusterJSON); ; for (FL_Cluster cluster : allClusters) { entityIds.addAll(cluster.getMembers()); for (FL_Property property : cluster.getProperties()) { if (!(property.getRange() instanceof FL_SingletonRange)) continue; FL_SingletonRange range = (FL_SingletonRange) property.getRange(); if (!range.getType().equals(FL_PropertyType.STRING)) continue; property.setRange( new SingletonRangeHelper( StringEscapeUtils.unescapeXml((String) range.getValue()))); } } final ContextReadWrite contextRW = contextCache.getReadWrite(nodeJSON.getString("xfId"), permits); contextRW.getContext().addClusters(allClusters); contextRW .getContext() .addEntities(entityAccess.getEntities(entityIds, FL_LevelOfDetail.SUMMARY)); contextRW.setSimplifiedContext(allClusters); } catch (IOException e) { throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "Exception during cluster cache processing.", e); } finally { permits.revoke(); } } currColumn = allColumns.get(columnIdx); while (rowIdx >= currColumn.size()) { currColumn.add(new JSONObject()); } currColumn.set(rowIdx, nodeJSON); } // place the files as children in the outgoing columns array for (int i = 0; i < allColumns.size(); i++) { columnJSON = outColumns.get(i); columnJSON.put("children", new JSONArray(allColumns.get(i))); } // finally, place the child columns and misc data in the resulting JSON object toReturn.put("children", new JSONArray(outColumns)); for (String dataKey : JSONObject.getNames(miscData)) { toReturn.put(dataKey, miscData.get(dataKey)); } return toReturn; }
/** * Scan the content following the named tag, attaching it to the context. * * @param x The XMLTokener containing the source string. * @param context The JSONObject that will include the new material. * @param name The tag name. * @return true if the close tag is processed. * @throws JSONException */ private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { char c; int i; JSONObject jsonobject = null; String string; String tagName; Object token; // Test for and skip past these forms: // <!-- ... --> // <! ... > // <![ ... ]]> // <? ... ?> // Report errors for these forms: // <> // <= // << token = x.nextToken(); // <! if (token == BANG) { c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); return false; } x.back(); } else if (c == '[') { token = x.nextToken(); if ("CDATA".equals(token)) { if (x.next() == '[') { string = x.nextCDATA(); if (string.length() > 0) { context.accumulate("content", string); } return false; } } throw x.syntaxError("Expected 'CDATA['"); } i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == LT) { i += 1; } else if (token == GT) { i -= 1; } } while (i > 0); return false; } else if (token == QUEST) { // <? x.skipPast("?>"); return false; } else if (token == SLASH) { // Close tag </ token = x.nextToken(); if (name == null) { throw x.syntaxError("Mismatched close tag " + token); } if (!token.equals(name)) { throw x.syntaxError("Mismatched " + name + " and " + token); } if (x.nextToken() != GT) { throw x.syntaxError("Misshaped close tag"); } return true; } else if (token instanceof Character) { throw x.syntaxError("Misshaped tag"); // Open tag < } else { tagName = (String) token; token = null; jsonobject = new JSONObject(); for (; ; ) { if (token == null) { token = x.nextToken(); } // attribute = value if (token instanceof String) { string = (String) token; token = x.nextToken(); if (token == EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } jsonobject.accumulate(string, XML.stringToValue((String) token)); token = null; } else { jsonobject.accumulate(string, ""); } // Empty tag <.../> } else if (token == SLASH) { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } if (jsonobject.length() > 0) { context.accumulate(tagName, jsonobject); } else { context.accumulate(tagName, ""); } return false; // Content, between <...> and </...> } else if (token == GT) { for (; ; ) { token = x.nextContent(); if (token == null) { if (tagName != null) { throw x.syntaxError("Unclosed tag " + tagName); } return false; } else if (token instanceof String) { string = (String) token; if (string.length() > 0) { jsonobject.accumulate("content", XML.stringToValue(string)); } // Nested element } else if (token == LT) { if (parse(x, jsonobject, tagName)) { if (jsonobject.length() == 0) { context.accumulate(tagName, ""); } else if (jsonobject.length() == 1 && jsonobject.opt("content") != null) { context.accumulate(tagName, jsonobject.opt("content")); } else { context.accumulate(tagName, jsonobject); } return false; } } } } else { throw x.syntaxError("Misshaped tag"); } } } }