Java Examples for org.json.XML

The following java examples will help you to understand the usage of org.json.XML. These source code samples are taken from different open source projects.

Example 1
Project: apiman-plugins-master  File: JsonToXmlTransformer.java View source code
@Override
public String transform(String json) {
    String ROOT = null;
    JSONObject jsonObject = null;
    if (//$NON-NLS-1$
    json.trim().startsWith("{")) {
        jsonObject = new JSONObject(json);
        if (jsonObject.length() > 1) {
            //$NON-NLS-1$
            ROOT = "root";
        }
    } else {
        JSONArray jsonArray = new JSONArray(json);
        jsonObject = new JSONObject().put(ELEMENT, jsonArray);
        //$NON-NLS-1$
        ROOT = "root";
    }
    return XML.toString(jsonObject, ROOT);
}
Example 2
Project: xcurator-master  File: Util.java View source code
public static String json2xml(String json) {
    JSONObject jsonObj = new JSONObject(json);
    String xml = XML.toString(jsonObj);
    xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<doc>" + xml + "</doc>";
    //        System.out.println(xml);
    Transformer transformer = null;
    try {
        transformer = TransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    }
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    //initialize StreamResult with File object to save to file
    StreamResult result = new StreamResult(new StringWriter());
    StreamSource source = new StreamSource(new StringReader(xml));
    try {
        transformer.transform(source, result);
    } catch (TransformerException ex) {
        Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
    }
    String prettyxml = result.getWriter().toString();
    return prettyxml;
}
Example 3
Project: ariadne-repository-master  File: ResultDelegateRFMEntity.java View source code
public String result(TopDocs topDocs, IndexSearcher searcher) throws Exception {
    Document doc;
    JSONObject json = new JSONObject();
    ScoreDoc[] hits = topDocs.scoreDocs;
    for (int i = start - 1; i < topDocs.totalHits && (max < 0 || i < start - 1 + max); i++) {
        doc = searcher.doc(hits[i].doc);
        try {
            json = XML.toJSONObject(doc.get("md"));
        } catch (JSONException e) {
            log.debug("result :: id=" + doc.get("key"), e);
            log.error(e);
        }
        log.debug(doc.get("key") + " = " + hits[i].score);
    }
    return json.toString();
}
Example 4
Project: nuxeo-master  File: PackageInfoTest.java View source code
@Test
public void testMarshalling() throws JAXBException, JSONException {
    JAXBContext jc = JAXBContext.newInstance(PackageInfo.class);
    Writer xml = new StringWriter();
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(packageInfo1, xml);
    log.debug(xml.toString());
    JSONObject entity = XML.toJSONObject(xml.toString()).getJSONObject("package");
    assertEquals(PackageVisibility.UNKNOWN, PackageVisibility.valueOf(entity.getString("visibility")));
    assertEquals(false, entity.getBoolean("supported"));
    assertEquals("test", entity.getString("name"));
    assertEquals(PackageState.UNKNOWN, PackageState.getByLabel(entity.getString("state")));
    assertEquals(false, entity.getBoolean("supportsHotReload"));
    assertEquals(new Version("1.0.0"), new Version(entity.getString("version")));
}
Example 5
Project: neoclipseWithCypherGenerator-master  File: DataExportUtils.java View source code
public static File exportToXml(String jsonString) throws Exception {
    File file = getFile(".xml");
    StringBuilder sb = new StringBuilder("<rootnode>");
    sb.append(XML.toString(new JSONArray(jsonString), "node"));
    sb.append("</rootnode>");
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    bw.write(sb.toString());
    bw.close();
    return file;
}
Example 6
Project: QlikWebServiceFramework-master  File: Get2Get_JSON2XML.java View source code
@GET
@Path("/")
public //@Consumes("application/json")
Response createProductInJSON(@Context HttpServletRequest request, @QueryParam("url") String url) {
    Response ret = null;
    try {
        /*
			 * Check the IP whitelist
			 */
        checkForAllowClient(request);
        ClientRequest proxyRequest = new ClientRequest(new URL(url).toExternalForm());
        proxyRequest.accept("application/json");
        ClientResponse<String> responseObj = proxyRequest.get(String.class);
        String responseBody = responseObj.getEntity(String.class);
        if (responseObj.getResponseStatus() != ClientResponse.Status.OK) {
            System.out.println("Called Faild");
            ret = Response.status(Status.INTERNAL_SERVER_ERROR).entity("").build();
        } else {
            //TODO: check to see if parsing should be done by and array [
            // or an object
            JSONArray json = new JSONArray(responseBody);
            String xml = XML.toString(json);
            ret = Response.status(Status.OK).entity(xml).build();
        }
    } catch (Exception e) {
        ret = Response.status(Status.INTERNAL_SERVER_ERROR).entity("").build();
        e.printStackTrace();
    }
    return ret;
}
Example 7
Project: replication-benchmarker-master  File: SizeJSonDoc.java View source code
public String gen(SimpleNode<String> in) {
    try {
        JSONObject xmlJSONObj = XML.toJSONObject("<?xml version=\"1.0\" ?>" + view(in));
        return xmlJSONObj.toString(0).replaceAll("\\s", "");
    } catch (JSONException ex) {
        Logger.getLogger(SizeJSonDoc.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}
Example 8
Project: voidbase-master  File: WebAPIQueueTreeHandler.java View source code
public String executeQuery(VoidBaseModuleRequest request) {
    try {
        QueueTreeModule queuetree = (QueueTreeModule) VoidBaseResourceRegister.getInstance().getHandler("queuetree");
        String xmlResponse = queuetree.buildResponse(request);
        //cast XML response to JSON string
        JSONResponse = XML.toJSONObject(xmlResponse).toString();
    } catch (Exception e) {
        System.err.println("Fatal error: " + e.getMessage());
    }
    return JSONResponse;
}
Example 9
Project: WhereIsMyCurrency-master  File: BankRequest.java View source code
@Override
protected List<Bank> parseStringToList(String str) throws JSONException {
    JSONObject jsonObj = XML.toJSONObject(str);
    JSONArray actualRates = jsonObj.getJSONObject("Exchange_Rates").getJSONObject("Actual_Rates").getJSONArray("Bank");
    Log.d(TAG, actualRates.toString());
    List<Bank> list = new ArrayList<>();
    for (int i = 0; i < actualRates.length(); i++) {
        try {
            BankJsonMapper interpreter = new BankJsonMapper();
            Bank bank = interpreter.modelToData(actualRates.getJSONObject(i));
            list.add(bank);
        } catch (Exception e) {
            Log.e(TAG, "parse error", e);
        }
    }
    return list;
}
Example 10
Project: Wikipedia-noSQL-Benchmark-master  File: terrastoreDB.java View source code
@Override
public int updateDB(String ID, String newValue) {
    int ret;
    org.json.JSONObject myjson = null;
    try {
        myjson = XML.toJSONObject(newValue);
    } catch (JSONException e1) {
        e1.printStackTrace();
    }
    try {
        newValue = myjson.toString();
        CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
        utf8Decoder.onMalformedInput(CodingErrorAction.REPLACE);
        utf8Decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
        ByteBuffer bytes = ByteBuffer.wrap(newValue.getBytes("UTF8"));
        CharBuffer parsed = utf8Decoder.decode(bytes);
        client.bucket("test").key(ID).put(parsed.toString());
        ret = 1;
    } catch (Exception e) {
        ret = -1;
        e.printStackTrace();
    }
    return ret;
}
Example 11
Project: xrd4j-master  File: XMLToJSONConverter.java View source code
/**
     * Converts the given XML string to JSON string. class.
     *
     * @param data XML string
     * @return JSON string or an empty string if the conversion fails
     */
@Override
public String convert(String data) {
    logger.debug("CONVERTING " + data);
    try {
        JSONObject asJson = XML.toJSONObject(data);
        if (asJson.has(ARRAY)) {
            // If the JSON object has an "array" key, it's an array
            JSONArray jsonArray = asJson.getJSONArray(ARRAY);
            logger.debug("RETURN ARRAY " + jsonArray.toString());
            return jsonArray.toString();
        } else {
            // Did not have top-level array key.
            this.normalizeObject(asJson);
            String jsonStr = asJson.toString();
            // JSON-LD uses '@' characters in keys and they're not allowed
            // in XML element names. Replace '__at__' with '@' in keys.
            jsonStr = jsonStr.replaceAll("\"__at__(.+?\"\\s*:)", "\"@$1");
            logger.debug("NORMALIZED TO " + jsonStr);
            return jsonStr;
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        logger.warn("Converting XML to JSON failed! An empty String is returned.");
        return "";
    }
}
Example 12
Project: CZ3003_Backend-master  File: CHazeManager.java View source code
public static void loadHazeInfo() {
    String strOutput = "";
    try {
        strOutput = CNetworkFactory.createHazeRequest().sendRequest();
    } catch (IOException ex) {
    }
    if (strOutput.isEmpty()) {
        return;
    }
    JSONArray aryRegions = XML.toJSONObject(strOutput).getJSONObject("channel").getJSONObject("item").getJSONArray("region");
    StringBuilder objSB = new StringBuilder();
    objSB.append("[");
    for (int i = 0; i < aryRegions.length(); i++) {
        objSB.append("{\"region\" : ");
        JSONObject objRegion = (JSONObject) aryRegions.get(i);
        objSB.append("\"");
        objSB.append(objRegion.getString("id"));
        objSB.append("\",");
        JSONArray aryReadings = objRegion.getJSONObject("record").getJSONArray("reading");
        for (int x = 0; x < aryReadings.length(); x++) {
            JSONObject objReading = (JSONObject) aryReadings.get(x);
            if (objReading.getString("type").equalsIgnoreCase("NPSI")) {
                objSB.append("\"psi\" : ");
                objSB.append(objReading.getInt("value"));
                objSB.append("},");
            }
        }
    }
    objSB.deleteCharAt(objSB.lastIndexOf(","));
    objSB.append("]");
    sendInfoToCPU(objSB.toString(), 33010);
}
Example 13
Project: loklak_server-master  File: AmazonProductService.java View source code
public static JSONObject fetchResults(String requestUrl, String operation) {
    JSONObject itemlookup = new JSONObject(true);
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(requestUrl);
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        JSONObject xmlresult = new JSONObject(true);
        xmlresult = XML.toJSONObject(writer.toString());
        JSONObject items = xmlresult.getJSONObject(operation).getJSONObject("Items");
        if (items.getJSONObject("Request").has("Errors")) {
            itemlookup.put("status", "error");
            itemlookup.put("reason", items.getJSONObject("Request").getJSONObject("Errors").getJSONObject("Error").get("Message"));
            return itemlookup;
        }
        itemlookup.put("number_of_items", (operation.equals("ItemLookupResponse") ? "1" : (items.getJSONArray("Item").length())));
        itemlookup.put("list_of_items", items);
    } catch (Exception e) {
        itemlookup.put("status", "error");
        itemlookup.put("reason", e);
        return itemlookup;
    }
    return itemlookup;
}
Example 14
Project: neoclipse-master  File: DataExportUtils.java View source code
public static File exportToXml(String jsonString) throws Exception {
    File file = getFile(".xml");
    StringBuilder sb = new StringBuilder("<rootnode>");
    sb.append(XML.toString(new JSONArray(jsonString), "node"));
    sb.append("</rootnode>");
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    bw.write(sb.toString());
    bw.close();
    return file;
}
Example 15
Project: Wilma-master  File: JsonConverter.java View source code
/**
     * Converts the given JSON data to XML.
     * @param json the given json data
     * @param rootName the root name of the generated xml
     * @return xml or an empty String if an error occurred
     */
@Override
public String convert(final String json, final String rootName) {
    String xml;
    try {
        JSONObject jsonObject = new JSONObject(json);
        xml = buildXMLFrom(XML.toString(jsonObject), rootName);
    } catch (JSONException e) {
        logger.debug("Couldn't convert to XML the following JSON: " + json, e);
        xml = "";
    }
    return xml;
}
Example 16
Project: iaf-master  File: JsonPipe.java View source code
public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    if (input == null) {
        throw new PipeRunException(this, getLogPrefix(session) + "got null input");
    }
    if (!(input instanceof String)) {
        throw new PipeRunException(this, getLogPrefix(session) + "got an invalid type as input, expected String, got " + input.getClass().getName());
    }
    try {
        String stringResult = (String) input;
        String dir = getDirection();
        if (dir.equalsIgnoreCase("json2xml")) {
            JSONTokener jsonTokener = new JSONTokener(stringResult);
            JSONObject jsonObject = new JSONObject(jsonTokener);
            stringResult = XML.toString(jsonObject);
        }
        if (dir.equalsIgnoreCase("xml2json")) {
            JSONObject jsonObject = XML.toJSONObject(stringResult);
            stringResult = jsonObject.toString();
        }
        return new PipeRunResult(getForward(), stringResult);
    } catch (Exception e) {
        throw new PipeRunException(this, getLogPrefix(session) + " Exception on transforming input", e);
    }
}
Example 17
Project: scooter-master  File: DefaultContentHandler.java View source code
protected <K, V> String convertMapToString(Map<K, V> map, String format) {
    StringBuilder sb = new StringBuilder();
    if ("json".equalsIgnoreCase(format)) {
        sb.append((new JSONObject(map)).toString());
    } else if ("xml".equalsIgnoreCase(format)) {
        try {
            sb.append(XML.toString((new JSONObject(map))));
        } catch (JSONException ex) {
            log.error("Failed to conver to xml string: " + ex.getMessage());
        }
    } else {
        sb.append(map.toString());
    }
    return sb.toString();
}
Example 18
Project: szeke-master  File: SampleDataFactory.java View source code
public static Worksheet createFromXMLTextFile(Workspace workspace, String fileName) {
    File xmlFile = new File(fileName);
    try {
        String fileContents = FileUtil.readFileContentsToString(xmlFile);
        // System.out.println(fileContents);
        // Converting the XML to JSON
        JSONObject json = XML.toJSONObject(fileContents);
        // System.err.println("JSON:" + o.toString());
        // System.err.println("JSON:" + JSONObject.quote(o.toString()));
        JsonImport ji = new JsonImport(json, fileName, workspace);
        Worksheet w = ji.generateWorksheet();
        return w;
    } catch (FileNotFoundException e) {
        logger.error("Cannot read file " + fileName + ".");
        e.printStackTrace();
    } catch (JSONException e) {
        logger.error("Could not parse JSON in file " + fileName + ".");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 19
Project: cougar-master  File: JSONHelpers.java View source code
public JSONObject convertXMLDocumentToJSONObjectRemoveRootElement(Document document) {
    try {
        /*
			 * We do not want to convert the root node to JSON, so get it, remove it's
			 * attributes, then when we return the JSONObject we can just get
			 * the JSONObject beneath the root. 
			 * 
			 * If we leave the attributes present then they will be included
			 * in the JSONObject beneath the root.
			 */
        if (document == null) {
            return null;
        } else {
            Node rootNode = document.getDocumentElement();
            NamedNodeMap namedNodeMap = rootNode.getAttributes();
            Integer numberOfAtts = Integer.valueOf(namedNodeMap.getLength());
            for (int i = 0; i < numberOfAtts; i++) {
                Node attributeNode = namedNodeMap.item(0);
                Element rootNodeAsElement = (Element) rootNode;
                rootNodeAsElement.removeAttribute(attributeNode.getNodeName());
            }
            String rootName = rootNode.getNodeName();
            String xmlString = xHelpers.getXMLAsString(document);
            JSONObject initialJSONObject = XML.toJSONObject(xmlString);
            String initialJSONString = initialJSONObject.toString();
            // try to take out dodgy null element conversions
            //                initialJSONString = initialJSONString.replace("{\"xsi:nil\":true,\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},","null,");
            //                initialJSONString = initialJSONString.replace(",{\"xsi:nil\":true,\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}",",null");
            //                initialJSONString = initialJSONString.replace(":{\"xsi:nil\":true,\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}","null");
            initialJSONString = initialJSONString.replace("{\"xsi:nil\":true,\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}", "null");
            initialJSONObject = new JSONObject(initialJSONString);
            JSONObject returnJSONObject;
            //if the result contains only one string value (like enum response)
            if (!initialJSONObject.get(rootName).getClass().equals(JSONObject.class)) {
                //create a Json object by adding a custom "response" key 
                returnJSONObject = new JSONObject().put("response", initialJSONObject.get(rootName));
            } else //				else if(!initialJSONObject.get(rootName).getClass().equals(JSONObject.class)){
            //					returnJSONObject = new JSONObject().put(initialJSONObject.get(rootName).getClass().getSimpleName(), initialJSONObject.get(rootName));
            //					
            //				}
            {
                returnJSONObject = (JSONObject) initialJSONObject.get(rootName);
            }
            //When converting from XML \n get set ro \r\n so fixing
            String jString = returnJSONObject.toString();
            jString = jString.replace("\\r\\n", "\\n");
            returnJSONObject = new JSONObject(jString);
            return returnJSONObject;
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}
Example 20
Project: iotdm-master  File: Onem2mXmlUtils.java View source code
public static String xmlRequestToJson(String content) {
    JSONObject cnResourceBody;
    boolean bodyOnly = true;
    //convert xml to json
    JSONObject cnJson = XML.toJSONObject(content);
    //postproccessing is needed to get valid onem2m resource json
    String maybeM2mKey = cnJson.keySet().toArray()[0].toString();
    if (cnJson.length() == 1 && maybeM2mKey.contains("m2m:")) {
        cnResourceBody = cnJson.optJSONObject(maybeM2mKey);
        bodyOnly = false;
    } else
        cnResourceBody = cnJson;
    //remove xmlns element property
    cnResourceBody.remove("xmlns:m2m");
    //fix arrays - common fields
    List<String> arrayFields = Arrays.asList(BaseResource.LABELS, BaseResource.ACCESS_CONTROL_POLICY_IDS, ResourceCse.POINT_OF_ACCESS, ResourceCse.SUPPORTED_RESOURCE_TYPES, ResourceAE.CONTENT_SERIALIZATION, ResourceSubscription.NOTIFICATION_URI);
    for (String field : arrayFields) {
        Object o = cnResourceBody.opt(field);
        if (o != null) {
            if (!(o instanceof JSONArray)) {
                cnResourceBody.put(field, Collections.singletonList(cnResourceBody.get(field).toString()));
            } else {
                JSONArray array = (JSONArray) o;
                ArrayList<String> strings = new ArrayList<String>(array.length());
                for (int i = 0; i < array.length(); i++) {
                    strings.add(array.get(i).toString());
                }
                cnResourceBody.put(field, strings);
            }
        }
    }
    //fix strings - common fields
    List<String> stringFields = Arrays.asList(ResourceContentInstance.CONTENT, RequestPrimitive.CONTENT_FORMAT, ResourceContentInstance.CONTENT_INFO, BaseResource.EXPIRATION_TIME, BaseResource.RESOURCE_NAME);
    for (String field : stringFields) {
        Object o = cnResourceBody.opt(field);
        if (o != null && !(o instanceof String)) {
            cnResourceBody.put(field, o.toString());
        }
    }
    //return json string
    return bodyOnly ? cnResourceBody.toString() : cnJson.put(maybeM2mKey, cnResourceBody).toString();
}
Example 21
Project: newton_adventure-master  File: JSONMapWriter.java View source code
/**
     * this method write a map OR a tileset in json format
     *
     * @param map
     * @param set
     * @param filename
     * @throws Exception
     */
private void writeMapOrTileset(Map map, TileSet set, String filename) throws Exception {
    // Create a temporary file
    File tempFile = File.createTempFile("tiled_json_", ".tmx");
    // Write in this temp file an xml content (tmx format)
    if (map != null) {
        super.writeMap(map, tempFile.getAbsolutePath());
    } else {
        if (set != null) {
            //write in this temp file an xml content (tmx format)
            super.writeTileset(set, tempFile.getAbsolutePath());
        } else
            return;
    }
    //TODO useful?
    tempFile = new File(tempFile.getAbsolutePath());
    // Now read this temp file and get the tmx content
    //TODO Replace here by true file size //(int) tempFile.length(); //100000;
    int fileSize = 100000;
    char[] TMXContent = new char[fileSize];
    FileReader fileR = new FileReader(tempFile.getAbsolutePath());
    fileR.read(TMXContent);
    fileR.close();
    // Avoid retrieving xml header like <?xml version=\"1.0\"?>, JSON parser doesn't like it!
    String TMXContentString = new String(TMXContent).trim().replaceFirst("\\<\\?.*\\?\\>", "");
    System.out.println("temp file path=" + tempFile.getAbsolutePath());
    System.out.println("filesize=" + fileSize);
    System.out.println("content=" + TMXContentString);
    // Delete useless temp file
    tempFile.delete();
    // Turn it into JSON format string
    String JSONContent = XML.toJSONObject(TMXContentString).toString(2);
    System.err.println("json content=" + JSONContent);
    // Write in destination file
    FileWriter fileW = new FileWriter(filename);
    fileW.write(JSONContent);
    fileW.flush();
    fileW.close();
}
Example 22
Project: weblounge-master  File: PageletEditor.java View source code
/**
   * Returns the <code>XML</code> representation of this pagelet.
   * 
   * @return the pagelet
   */
public String toXml() {
    StringBuffer buf = new StringBuffer();
    // head
    buf.append("<pageleteditor ");
    buf.append("name=\"").append(renderer.getName()).append("\" ");
    buf.append("module=\"").append(renderer.getModule().getName()).append("\" ");
    buf.append("uri=\"").append(uri.getIdentifier()).append("\" ");
    buf.append("composer=\"").append(composerId).append("\" ");
    buf.append("index=\"").append(pageletIndex).append("\">");
    // the pagelet
    buf.append("<data flavor=\"").append(dataFlavor.toString().toLowerCase()).append("\">");
    String data = null;
    switch(dataFlavor) {
        case Json:
            try {
                data = "<![CDATA[" + XML.toJSONObject(pagelet.toXml()).toString() + "]]>";
            } catch (JSONException e) {
                throw new IllegalStateException("Pagelet xml can't be converted to json: " + e.getMessage(), e);
            }
            break;
        case Xml:
            data = pagelet.toXml();
            break;
        default:
            throw new IllegalStateException("An unhandled flavor was found: " + dataFlavor);
    }
    buf.append(data);
    buf.append("</data>");
    // the editor
    if (editorContents != null) {
        buf.append("<editor type=\"xhtml\"><![CDATA[");
        buf.append(editorContents);
        buf.append("]]></editor>");
    }
    // HTML head elements
    Module m = renderer.getModule();
    for (HTMLHeadElement headElement : renderer.getHTMLHeaders()) {
        buf.append(ConfigurationUtils.processTemplate(headElement.toXml(), m, environment));
    }
    buf.append("</pageleteditor>");
    return buf.toString();
}
Example 23
Project: Wink-master  File: JsonJAXBProvider.java View source code
public void writeTo(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    try {
        mediaType = MediaTypeUtils.setDefaultCharsetOnMediaTypeHeader(httpHeaders, mediaType);
        @SuppressWarnings("unchecked") MessageBodyWriter<Object> jaxbWriter = (MessageBodyWriter<Object>) providers.getMessageBodyWriter(type, genericType, annotations, MediaType.APPLICATION_XML_TYPE);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        jaxbWriter.writeTo(t, type, genericType, annotations, MediaType.APPLICATION_XML_TYPE, httpHeaders, os);
        JSONObject json = XML.toJSONObject(os.toString());
        bodyWriter.writeTo(json, JSONObject.class, JSONObject.class, annotations, mediaType, httpHeaders, entityStream);
    } catch (JSONException e) {
        throw new WebApplicationException(e);
    }
}
Example 24
Project: paxml-master  File: JsonXml.java View source code
/**
     * 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 (BANG.equals(token)) {
        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(VALUE, string);
                    }
                    return false;
                }
            }
            throw x.syntaxError("Expected 'CDATA['");
        }
        i = 1;
        do {
            token = x.nextMeta();
            if (token == null) {
                throw x.syntaxError("Missing '>' after '<!'.");
            } else if (LT.equals(token)) {
                i += 1;
            } else if (GT.equals(token)) {
                i -= 1;
            }
        } while (i > 0);
        return false;
    } else if (QUEST.equals(token)) {
        // <?
        x.skipPast("?>");
        return false;
    } else if (SLASH.equals(token)) {
        // 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 (!GT.equals(x.nextToken())) {
            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();
            }
            if (token instanceof String) {
                string = (String) token;
                token = x.nextToken();
                if (EQ.equals(token)) {
                    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 (SLASH.equals(token)) {
                if (!GT.equals(x.nextToken())) {
                    throw x.syntaxError("Misshaped tag");
                }
                if (jsonobject.length() > 0) {
                    context.accumulate(tagName, jsonobject);
                } else {
                    context.accumulate(tagName, "");
                }
                return false;
            // Content, between <...> and </...>
            } else if (GT.equals(token)) {
                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(VALUE, XML.stringToValue(string));
                        }
                    // Nested element
                    } else if (LT.equals(token)) {
                        if (parse(x, jsonobject, tagName)) {
                            if (jsonobject.length() == 0) {
                                context.accumulate(tagName, "");
                            } else if (jsonobject.length() == 1 && jsonobject.opt(VALUE) != null) {
                                context.accumulate(tagName, jsonobject.opt(VALUE));
                            } else {
                                context.accumulate(tagName, jsonobject);
                            }
                            return false;
                        }
                    }
                }
            } else {
                throw x.syntaxError("Misshaped tag");
            }
        }
    }
}
Example 25
Project: droolsjbpm-integration-master  File: FormResource.java View source code
protected String marshallFormContent(String formContent, String formType, Variant variant) throws Exception {
    if (StringUtils.isEmpty(formContent)) {
        return formContent;
    }
    FormServiceBase.FormType actualFormType = FormServiceBase.FormType.fromName(formType);
    String actualContentType = actualFormType.getContentType();
    if (actualContentType == null) {
        actualContentType = getMediaTypeForFormContent(formContent);
    }
    if (variant.getMediaType().equals(MediaType.APPLICATION_JSON_TYPE) && !MediaType.APPLICATION_JSON_TYPE.getSubtype().equals(actualContentType)) {
        JSONObject json = XML.toJSONObject(formContent);
        formatJSONResponse(json);
        formContent = json.toString(PRETTY_PRINT_INDENT_FACTOR);
    } else if (variant.getMediaType().equals(MediaType.APPLICATION_XML_TYPE) && !MediaType.APPLICATION_XML_TYPE.getSubtype().equals(actualContentType)) {
        Object json = parseToJSON(formContent);
        formContent = XML.toString(json);
    }
    return formContent;
}
Example 26
Project: FutureSonic-Server-master  File: XMLBuilder.java View source code
/**
     * Returns the XML document as a string.
     */
@Override
public String toString() {
    String xml = writer.toString();
    if (!json) {
        return xml;
    }
    try {
        JSONObject jsonObject = XML.toJSONObject(xml);
        if (jsonpCallback != null) {
            return jsonpCallback + "(" + jsonObject.toString(1) + ");";
        }
        return jsonObject.toString(1);
    } catch (JSONException x) {
        throw new RuntimeException("Failed to convert from XML to JSON.", x);
    }
}
Example 27
Project: GeoprocessingAppstore-master  File: ResourceReader.java View source code
/**
   * Reads a JSON response from an ArcGIS server Rest end-point and converts it to an
   * XML string.
   * @param url the rest URL to the ArcGIS service 
   * @return the rest response as an XML String
   * @throws MalformedURLException if the URL is invalid
   * @throws IOException if the communication fails
   * @throws JSONException if a non-empty response could not be 
   *         loaded as a JSON onject or conversion to XML fails
   * @throws TransformerFactoryConfigurationError configuration related exception
   * @throws TransformerException transformation related exception
   */
private String readAgsXml(String url) throws MalformedURLException, IOException, JSONException, TransformerFactoryConfigurationError, TransformerException {
    String xml = "";
    JSONObject jso = readAgsJson(url);
    if (jso != null) {
        try {
            JSONObject jsoError = jso.getJSONObject("error");
            if (jsoError != null) {
                throw new IOException(jsoError.toString());
            }
        } catch (JSONException e) {
        }
        if (autoRecurse) {
            parseAgsTree(jso);
            for (String service : this.agsServiceUrls) System.err.println(service);
        }
        xml = toAgsXml(jso);
        LOGGER.finer("ArcGIS Rest/JSON to XML\n" + xml);
    }
    return xml;
}
Example 28
Project: madsonic-server-4.7-master  File: XMLBuilder.java View source code
/**
     * Returns the XML document as a string.
     */
@Override
public String toString() {
    String xml = writer.toString();
    if (!json) {
        return xml;
    }
    try {
        JSONObject jsonObject = XML.toJSONObject(xml);
        if (jsonpCallback != null) {
            return jsonpCallback + "(" + jsonObject.toString(1) + ");";
        }
        return jsonObject.toString(1);
    } catch (JSONException x) {
        throw new RuntimeException("Failed to convert from XML to JSON.", x);
    }
}
Example 29
Project: madsonic-server-5.0-master  File: XMLBuilder.java View source code
/**
     * Returns the XML document as a string.
     */
@Override
public String toString() {
    String xml = writer.toString();
    if (!json) {
        return xml;
    }
    try {
        JSONObject jsonObject = XML.toJSONObject(xml);
        if (jsonpCallback != null) {
            return jsonpCallback + "(" + jsonObject.toString(1) + ");";
        }
        return jsonObject.toString(1);
    } catch (JSONException x) {
        throw new RuntimeException("Failed to convert from XML to JSON.", x);
    }
}
Example 30
Project: nextreports-engine-master  File: JSONFullExporter.java View source code
protected void finishExport() {
    try {
        XStream xstream = XStreamFactory.createXStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        xstream.toXML(bean.getReportLayout(), bos);
        JSONObject node = XML.toJSONObject(bos.toString());
        ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
        xstream.toXML(bean.getParametersBean().getParamValues(), bos2);
        JSONObject node2 = XML.toJSONObject(bos2.toString());
        getStream().print("],");
        // report layout
        String repLayout = node.toString();
        repLayout = repLayout.substring(repLayout.indexOf("{") + 1, repLayout.lastIndexOf("}"));
        getStream().print(repLayout);
        getStream().print(",");
        // parameters bean
        String parLayout = node2.toString();
        parLayout = parLayout.substring(parLayout.indexOf("{") + 1);
        getStream().print(parLayout);
    } catch (Exception e) {
        e.printStackTrace();
        getStream().print("]}");
    }
    getStream().flush();
    if (!bean.isSubreport()) {
        getStream().close();
    }
}
Example 31
Project: restx-master  File: MavenSupport.java View source code
public ModuleDescriptor parse(InputStream stream) throws IOException {
    JSONObject jsonObject = XML.toJSONObject(RestxBuildHelper.toString(stream)).getJSONObject("project");
    GAV parent;
    if (jsonObject.has("parent")) {
        JSONObject parentObject = jsonObject.getJSONObject("parent");
        // No packaging type is allowed on <parent> tag
        parent = getGav(parentObject, null);
    } else {
        parent = null;
    }
    // Packaging is defined with <packaging> tag on artefact definition
    GAV gav = getGav(jsonObject, "packaging");
    String packaging = jsonObject.has("packaging") ? jsonObject.getString("packaging") : "jar";
    Map<String, String> properties = new LinkedHashMap<>();
    if (jsonObject.has("properties")) {
        JSONObject props = jsonObject.getJSONObject("properties");
        for (Object o : props.keySet()) {
            String p = (String) o;
            if (p.equals("maven.compiler.target") || p.equals("maven.compiler.source")) {
                properties.put("java.version", String.valueOf(props.get(p)));
            } else {
                properties.put(p, String.valueOf(props.get(p)));
            }
        }
    }
    Map<String, List<ModuleDependency>> dependencies = new LinkedHashMap<>();
    if (jsonObject.has("dependencies")) {
        JSONArray deps = jsonObject.getJSONObject("dependencies").getJSONArray("dependency");
        for (int i = 0; i < deps.length(); i++) {
            JSONObject dep = deps.getJSONObject(i);
            String scope = dep.has("scope") ? dep.getString("scope") : "compile";
            List<ModuleDependency> scopeDependencies = dependencies.get(scope);
            if (scopeDependencies == null) {
                dependencies.put(scope, scopeDependencies = new ArrayList<>());
            }
            // Packaging is defined with <type> tag on dependencies
            scopeDependencies.add(new ModuleDependency(getGav(dep, "type")));
        }
    }
    return new ModuleDescriptor(parent, gav, packaging, properties, new HashMap<String, List<ModuleFragment>>(), dependencies);
}
Example 32
Project: subsonic-mods-jcduss-master  File: XMLBuilder.java View source code
/**
     * Returns the XML document as a string.
     */
@Override
public String toString() {
    String xml = writer.toString();
    if (!json) {
        return xml;
    }
    try {
        JSONObject jsonObject = XML.toJSONObject(xml);
        if (jsonpCallback != null) {
            return jsonpCallback + "(" + jsonObject.toString(1) + ");";
        }
        return jsonObject.toString(1);
    } catch (JSONException x) {
        throw new RuntimeException("Failed to convert from XML to JSON.", x);
    }
}
Example 33
Project: supersonic-master  File: XMLBuilder.java View source code
/**
     * Returns the XML document as a string.
     */
@Override
public String toString() {
    String xml = writer.toString();
    if (!json) {
        return xml;
    }
    try {
        JSONObject jsonObject = XML.toJSONObject(xml);
        if (jsonpCallback != null) {
            return jsonpCallback + "(" + jsonObject.toString(1) + ");";
        }
        return jsonObject.toString(1);
    } catch (JSONException x) {
        throw new RuntimeException("Failed to convert from XML to JSON.", x);
    }
}
Example 34
Project: testsuite-nocoding-master  File: XPathWithNonParseableWebResponse.java View source code
private void createXMLSourceFromWebResponseContent() throws ParserConfigurationException, SAXException, IOException {
    XltLogger.runTimeLogger.debug("Loading content from WebResponse");
    final String contentType = getContentTypeFromWebResponse();
    final String bodyContent = this.webResponse.getContentAsString();
    if (JSON.equals(contentType)) {
        this.xmlInputSource = createXMLSourceFromJson(bodyContent);
    } else if (XML.equals(contentType)) {
        this.xmlInputSource = createXMLSourceFromXML(bodyContent);
    } else {
        throw new IllegalArgumentException("This will never happen!");
    }
}
Example 35
Project: uPortal-master  File: ImportExportController.java View source code
protected BufferedXMLEventReader createSourceXmlEventReader(MultipartFile multipartFile) throws IOException {
    final InputStream inputStream = multipartFile.getInputStream();
    final String name = multipartFile.getOriginalFilename();
    final XMLInputFactory xmlInputFactory = this.xmlUtilities.getXmlInputFactory();
    final XMLEventReader xmlEventReader;
    try {
        xmlEventReader = xmlInputFactory.createXMLEventReader(name, inputStream);
    } catch (XMLStreamException e) {
        throw new RuntimeException("Failed to create XML Event Reader for data Source", e);
    }
    return new BufferedXMLEventReader(xmlEventReader, -1);
}
Example 36
Project: vitam-master  File: Xml2JsonTest.java View source code
@Test
public void testUsingJSONObject() throws InvalidParseOperationException {
    final JSONObject xml = XML.toJSONObject(XML_SRC);
    final JsonNode json = JsonHandler.getFromString(xml.toString());
    LOGGER.warn(JsonHandler.prettyPrint(json));
    assertTrue(json.get("Aaa").get("Bbb").isArray());
    assertTrue(json.get("Aaa").get("Bbb").size() == 4);
    assertTrue(json.get("Aaa").get("Ddd").get("Bbb").size() == 3);
    LOGGER.warn(XML.toString(xml));
}
Example 37
Project: Web-Karma-master  File: SampleDataFactory.java View source code
public static Worksheet createFromXMLTextFile(Workspace workspace, String fileName) {
    File xmlFile = new File(fileName);
    try {
        String fileContents = FileUtil.readFileContentsToString(xmlFile, "UTF-8");
        // Converting the XML to JSON
        JSONObject json = XML.toJSONObject(fileContents);
        JsonImport ji = new JsonImport(json, fileName, workspace, "UTF-8", -1);
        Worksheet w = ji.generateWorksheet();
        return w;
    } catch (FileNotFoundException e) {
        logger.error("Cannot read file " + fileName + ".");
        e.printStackTrace();
    } catch (JSONException e) {
        logger.error("Could not parse JSON in file " + fileName + ".");
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 38
Project: act-master  File: SeqIdentMapper.java View source code
private Set<SequenceEntry> web_lookup(AccID acc) {
    Set<SequenceEntry> entries = new HashSet<SequenceEntry>();
    try {
        switch(acc.db) {
            // fallthrough
            case swissprot:
            // fallthrough
            case uniprot:
            // fallthrough
            case embl:
            case trembl:
                String api_xml = web_uniprot(acc.acc_num);
                entries = SwissProtEntry.parsePossiblyMany(api_xml);
                break;
            case genbank:
                String try_uniprot = web_uniprot(acc.acc_num);
                if (!try_uniprot.equals("")) {
                    api_xml = try_uniprot;
                    entries = SwissProtEntry.parsePossiblyMany(api_xml);
                } else {
                    api_xml = web_genbank(acc.acc_num);
                    entries = GenBankEntry.parsePossiblyMany(api_xml);
                }
                break;
            default:
                System.out.println("Unrecognized AccDB = " + acc.db);
                System.exit(-1);
                return null;
        }
        if (entries.size() > 1) {
            // System.out.println("Multiple entries: " + entries);
            System.out.println("XML from api call returned > 1 entry");
        // System.console().readLine();
        }
    } catch (IOException e) {
        System.err.println("Caught IOException when attempting to look up accession number " + acc.acc_num + " in " + acc.db);
        e.printStackTrace(System.err);
    }
    return entries;
}
Example 39
Project: Edge-Node-master  File: JSONFeedParser.java View source code
public static String parseFromJSONToAlchemy(Document xmlFeed) throws Exception {
    // Parse XML to JSON
    DOMSource domSource = new DOMSource(xmlFeed);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, result);
    String xml = writer.toString();
    // System.out.println(writer.toString() );
    int endOfFirstLine = xml.indexOf('\n');
    int beginingOfLastLine = xml.lastIndexOf("</rdf>");
    xml = xml.substring(endOfFirstLine + 1, beginingOfLastLine - 1);
    JSONObject rootElement = XML.toJSONObject(xml);
    JSONObject measurementTree = rootElement.getJSONObject("measurement");
    String measurementTime = measurementTree.getString("time");
    JSONArray crowd = measurementTree.getJSONArray("crowd");
    StringBuilder observations = new StringBuilder();
    for (int i = 0; i < Math.min(crowd.length() - 1, 1); i++) {
        JSONObject crowdMeasurements = crowd.getJSONObject(i);
        Double densityValue = (Double) crowdMeasurements.get("density");
        System.out.print("Density:" + densityValue);
        String densityString = "";
        if (densityValue < 0.015)
            densityString = "Low";
        else
            densityString = "High";
        observations.append("CrowdDensityMeasurementValue(" + densityString + ")\n");
    }
    System.out.println(", time: " + measurementTime);
    return observations.toString();
}
Example 40
Project: cirilo-master  File: STORY.java View source code
public boolean set(String file, boolean eXist) {
    String stream = null;
    int n;
    try {
        this.PID = "";
        if (!eXist) {
            this.file = new File(file);
            this.collection = "";
            if (this.file.exists()) {
                char[] buff = new char[1024];
                StringWriter sw = new StringWriter();
                FileInputStream is = new FileInputStream(file);
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                try {
                    while ((n = br.read(buff)) != -1) {
                        sw.write(buff, 0, n);
                    }
                    stream = sw.toString();
                } catch (Exception io) {
                    sw.close();
                    br.close();
                }
            }
        } else {
            eXist eX = new eXist(file);
            org.xmldb.api.base.Collection collection = DatabaseManager.getCollection(URI + eX.getCollection(), user.getExistUser(), user.getExistPasswd());
            XMLResource res = (XMLResource) collection.getResource(eX.getStream());
            stream = (String) res.getContent();
            collection.close();
            this.collection = file;
        }
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        return false;
    }
    try {
        this.raw = stream;
        if (stream.contains("\"storymap\":")) {
            JSONObject json = new JSONObject(stream);
            stream = XML.toString(json);
        }
        this.story = builder.build(new StringReader(stream));
        return true;
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
        return false;
    }
}
Example 41
Project: drive-uploader-master  File: DriveResumableUpload.java View source code
public String getFileId() throws IOException {
    logger.info("Querying file id of completed upload...");
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {
        httpclient = getHttpClient();
        BasicHttpRequest httpreq = new BasicHttpRequest("PUT", location);
        httpreq.addHeader("Authorization", auth.getAuthHeader());
        httpreq.addHeader("Content-Length", "0");
        httpreq.addHeader("Content-Range", "bytes */" + getFileSizeString());
        response = httpclient.execute(URIUtils.extractHost(uri), httpreq);
        BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());
        EntityUtils.consume(response.getEntity());
        String retSrc = EntityUtils.toString(entity);
        if (useOldApi) {
            // Old API will return XML!
            JSONObject result = XML.toJSONObject(retSrc);
            return result.getJSONObject("entry").getString("gd:resourceId").replace("file:", "");
        } else {
            JSONObject result = new JSONObject(retSrc);
            return result.getString("id");
        }
    } finally {
        if (response != null) {
            response.close();
        }
        if (httpclient != null) {
            httpclient.close();
        }
    }
}
Example 42
Project: h2o-2-master  File: Request.java View source code
public NanoHTTPD.Response serveResponse(NanoHTTPD server, Properties parms, RequestType type, Response response) {
    // for transition between v1 and v2 API
    if (this instanceof Request2)
        ((Request2) this).fillResponseInfo(response);
    // FIXME: Parser2 should inherit from Request2
    if (this instanceof Parse2)
        ((Parse2) this).fillResponseInfo(response);
    if (type == RequestType.json) {
        return //
        response._req == null ? //
        wrap(server, response.toJson()) : wrap(server, new String(response._req.writeJSON(new AutoBuffer()).buf()), RequestType.json);
    } else if (type == RequestType.xml) {
        if (response._req == null) {
            String xmlString = response.toXml();
            NanoHTTPD.Response r = wrap(server, xmlString, RequestType.xml);
            return r;
        } else {
            String jsonString = new String(response._req.writeJSON(new AutoBuffer()).buf());
            org.json.JSONObject jo2 = new org.json.JSONObject(jsonString);
            String xmlString = org.json.XML.toString(jo2);
            NanoHTTPD.Response r = wrap(server, xmlString, RequestType.xml);
            return r;
        }
    }
    return wrap(server, build(response));
}
Example 43
Project: mekhq-master  File: MekHqXmlUtil.java View source code
public static Entity getEntityFromXmlString(String xml) throws UnsupportedEncodingException {
    MekHQ.logMessage("Executing getEntityFromXmlString(String)...", 4);
    Entity retVal = null;
    MULParser prs = new MULParser(new ByteArrayInputStream(xml.getBytes("UTF-8")));
    Vector<Entity> ents = prs.getEntities();
    if (ents.size() > 1)
        throw new IllegalArgumentException("More than one entity contained in XML string!  Expecting a single entity.");
    else if (ents.size() != 0)
        retVal = ents.get(0);
    MekHQ.logMessage("Returning " + retVal + " from getEntityFromXmlString(String)...", 4);
    return retVal;
}
Example 44
Project: MusesServer-master  File: TestPolicyRulesTransmitter.java View source code
/**
	  * testSendPolicyDT - JUnit test case whose aim is to test the communication method to send a set of policy decision entries to a concrete device
	  *
	  * @param policyDT - Set of policy decision entries
	  * @param device - Target device, identified by MUSES
	  * 
	  */
public final void testSendPolicyDTV1() {
    String dataToSend = null;
    String sessionId = "572H562LH72472OU4K";
    try {
        InputStream in = FileManager.get().open("devpolicies/muses-device-policy-prototype.xml");
        InputStreamReader is = new InputStreamReader(in);
        StringBuilder sb = new StringBuilder();
        BufferedReader br = new BufferedReader(is);
        String read = br.readLine();
        while (read != null) {
            sb.append(read);
            read = br.readLine();
        }
        String fileContent = sb.toString();
        JSONObject xmlJSONObj = XML.toJSONObject(fileContent);
        dataToSend = xmlJSONObj.toString();
    } catch (JSONException je) {
        je.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    PolicyDT policy = new PolicyDT();
    policy.setRawPolicy(dataToSend);
    Device device = new Device();
    PolicyTransmitter transmitter = new PolicyTransmitter();
    assertNotNull(transmitter.sendPolicyDT(policy, device, sessionId));
}
Example 45
Project: nomulus-master  File: XmlTestUtils.java View source code
public static void assertXmlEqualsWithMessage(String expected, String actual, String message, String... ignoredPaths) throws Exception {
    if (!actual.startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")) {
        assert_().fail("XML declaration not found at beginning:\n%s", actual);
    }
    Map<String, Object> expectedMap = toComparableJson(expected, ignoredPaths);
    Map<String, Object> actualMap = toComparableJson(actual, ignoredPaths);
    if (!expectedMap.equals(actualMap)) {
        assert_().fail(String.format("%s: Expected:\n%s\n\nActual:\n%s\n\nDiff:\n%s\n\n", message, expected, actual, prettyPrintXmlDeepDiff(expectedMap, actualMap, null)));
    }
}
Example 46
Project: opencms-core-master  File: XML.java View source code
/**
     * Convert a JSONObject into a well-formed, element-normal XML string.<p>
     * 
     * @param o a JSONObject
     * @param tagName the optional name of the enclosing tag
     * @return a string
     * @throws JSONException if something goes wrong
     */
public static String toString(Object o, String tagName) throws JSONException {
    StringBuffer b = new StringBuffer();
    int i;
    JSONArray ja;
    JSONObject jo;
    String k;
    Iterator keys;
    int len;
    String s;
    Object v;
    if (o instanceof JSONObject) {
        if (tagName != null) {
            b.append('<');
            b.append(tagName);
            b.append('>');
        }
        // Loop thru the keys.
        jo = (JSONObject) o;
        keys = jo.keys();
        while (keys.hasNext()) {
            k = keys.next().toString();
            v = jo.get(k);
            if (v instanceof String) {
                s = (String) v;
            } else {
                s = null;
            }
            if (k.equals("content")) {
                if (v instanceof JSONArray) {
                    ja = (JSONArray) v;
                    len = ja.length();
                    for (i = 0; i < len; i += 1) {
                        if (i > 0) {
                            b.append('\n');
                        }
                        b.append(escape(ja.get(i).toString()));
                    }
                } else {
                    b.append(escape(v.toString()));
                }
            // Emit an array of similar keys
            } else if (v instanceof JSONArray) {
                ja = (JSONArray) v;
                len = ja.length();
                for (i = 0; i < len; i += 1) {
                    b.append(toString(ja.get(i), k));
                }
            } else if (v.equals("")) {
                b.append('<');
                b.append(k);
                b.append("/>");
            // Emit a new tag <k>
            } else {
                b.append(toString(v, k));
            }
        }
        if (tagName != null) {
            // Emit the </tagname> close tag
            b.append("</");
            b.append(tagName);
            b.append('>');
        }
        return b.toString();
    // XML does not have good support for arrays. If an array appears in a place
    // where XML is lacking, synthesize an <array> element.
    } else if (o instanceof JSONArray) {
        ja = (JSONArray) o;
        len = ja.length();
        for (i = 0; i < len; ++i) {
            b.append(toString(ja.opt(i), (tagName == null) ? "array" : tagName));
        }
        return b.toString();
    } else {
        s = (o == null) ? "null" : escape(o.toString());
        return (tagName == null) ? "\"" + s + "\"" : (s.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + s + "</" + tagName + ">";
    }
}
Example 47
Project: opencms-master  File: XML.java View source code
/**
     * Convert a JSONObject into a well-formed, element-normal XML string.<p>
     * 
     * @param o a JSONObject
     * @param tagName the optional name of the enclosing tag
     * @return a string
     * @throws JSONException if something goes wrong
     */
public static String toString(Object o, String tagName) throws JSONException {
    StringBuffer b = new StringBuffer();
    int i;
    JSONArray ja;
    JSONObject jo;
    String k;
    Iterator keys;
    int len;
    String s;
    Object v;
    if (o instanceof JSONObject) {
        if (tagName != null) {
            b.append('<');
            b.append(tagName);
            b.append('>');
        }
        // Loop thru the keys.
        jo = (JSONObject) o;
        keys = jo.keys();
        while (keys.hasNext()) {
            k = keys.next().toString();
            v = jo.get(k);
            if (v instanceof String) {
                s = (String) v;
            } else {
                s = null;
            }
            if (k.equals("content")) {
                if (v instanceof JSONArray) {
                    ja = (JSONArray) v;
                    len = ja.length();
                    for (i = 0; i < len; i += 1) {
                        if (i > 0) {
                            b.append('\n');
                        }
                        b.append(escape(ja.get(i).toString()));
                    }
                } else {
                    b.append(escape(v.toString()));
                }
            // Emit an array of similar keys
            } else if (v instanceof JSONArray) {
                ja = (JSONArray) v;
                len = ja.length();
                for (i = 0; i < len; i += 1) {
                    b.append(toString(ja.get(i), k));
                }
            } else if (v.equals("")) {
                b.append('<');
                b.append(k);
                b.append("/>");
            // Emit a new tag <k>
            } else {
                b.append(toString(v, k));
            }
        }
        if (tagName != null) {
            // Emit the </tagname> close tag
            b.append("</");
            b.append(tagName);
            b.append('>');
        }
        return b.toString();
    // XML does not have good support for arrays. If an array appears in a place
    // where XML is lacking, synthesize an <array> element.
    } else if (o instanceof JSONArray) {
        ja = (JSONArray) o;
        len = ja.length();
        for (i = 0; i < len; ++i) {
            b.append(toString(ja.opt(i), (tagName == null) ? "array" : tagName));
        }
        return b.toString();
    } else {
        s = (o == null) ? "null" : escape(o.toString());
        return (tagName == null) ? "\"" + s + "\"" : (s.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + s + "</" + tagName + ">";
    }
}
Example 48
Project: OWL-S-Restful-master  File: WADLAtomicGroundingImpl.java View source code
/* (non-Javadoc)
	 * @see org.mindswap.owls.grounding.AtomicGrounding#invoke(org.mindswap.query.ValueMap, org.mindswap.owl.OWLKnowledgeBase)
	 */
public Future<ValueMap<Output, OWLValue>> invoke(ValueMap<Input, OWLValue> inputs, OWLKnowledgeBase env) {
    try {
        initWADLResource();
        for (final WADLParameter in : wadlResource.getInputs()) {
            final MessageMap<TransformationFileMap> mp = getMessageMap(true, in.getId());
            if (mp == null)
                continue;
            final Input input = mp.getOWLSParameter().castTo(Input.class);
            OWLValue inputValue = null;
            try {
                inputValue = getParameterValue(input, inputs);
            } catch (ExecutionException e) {
                if (in.getValue() != null) {
                    inputValue = env.createDataValue(in.getValue());
                    inputs.setValue(input, inputValue);
                }
            }
            if (inputValue != null) {
                Object inputValueObj;
                TransformationFileMap transf = mp.getTransformation();
                String xslt = null;
                if (transf != null)
                    xslt = transf.getTransformationURI().toString();
                if (inputValue.isIndividual()) {
                    final String rdfXML = ((OWLIndividual) inputValue).toRDF(true, true);
                    if (xslt != null) {
                        final String xsltResult = XSLTEngine.transform(rdfXML, xslt, inputs);
                        inputValueObj = Utils.getAsNode(xsltResult);
                        if (inputValueObj == null)
                            inputValueObj = xsltResult.trim();
                    } else {
                        logger.debug("No XSLT transformation for input parameter " + input + " specified." + " OWLIndividual bound to this parameter should be transformed rather than using" + " its RDF/XML serialization.");
                        inputValueObj = rdfXML;
                    }
                } else // it is a OWLDataValue
                {
                    if (xslt != null)
                        throw new ExecutionException("XSLT transformation for input parameter " + input + " cannot be applied to OWL data value (only to OWL individual).");
                    inputValueObj = ((OWLDataValue) inputValue).getValue();
                }
                in.setValue(inputValueObj);
            }
        }
        wadlResource.invoke();
        final ValueMap<Output, OWLValue> results = new ValueMap<Output, OWLValue>();
        for (final Output outputParam : getProcess().getOutputs()) {
            final MessageMap<TransformationFileMap> mp = getMessageMap(outputParam);
            final TransformationFileMap transformation = mp.getTransformation();
            final String wadlMessageParam = mp.getGroundingParameter();
            WADLParameter out = wadlResource.getOutput(wadlMessageParam);
            //WADLParameter out = wadlResource.getRepresentation();
            Object outputValue = out.getValue();
            if (outputValue != null) {
                if (outputParam.getParamType().isDataType()) {
                    results.setValue(outputParam, env.createDataValue(outputValue));
                } else {
                    String outputString = outputValue.toString();
                    if (out.getMediaType().indexOf("json") > -1 || out.getMediaType().indexOf("javascript") > -1) {
                        Object obj = null;
                        try {
                            obj = new JSONObject(outputString);
                        } catch (Exception e) {
                            obj = new JSONArray(outputString);
                        }
                        if (obj != null)
                            outputString = XML.toString(obj, "json");
                    }
                    if (transformation != null && transformation.getTransformationMediaType().indexOf("xsl") > -1) {
                        WADLRequest req = new WADLRequestImpl();
                        String xslt = (String) req.request(transformation.getTransformationURI().toString(), "GET");
                        outputString = XSLTEngine.transform(outputString, xslt, inputs);
                        results.setValue(outputParam, env.parseLiteral(outputString));
                    } else {
                        results.setValue(outputParam, env.createDataValue(outputString));
                    }
                }
            }
        }
        return CompletedFuture.createSuccessCompletionFuture(results);
    } catch (final Exception e) {
        return CompletedFuture.createExceptionCompletionFuture(e);
    }
}
Example 49
Project: route-monitor-for-geoevent-master  File: WorkOrdersActivity.java View source code
private void readStopConfigFromLocal() {
    try {
        InputStream inputStream = openFileInput(stopConfigFileName);
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((receiveString = bufferedReader.readLine()) != null) {
                stringBuilder.append(receiveString);
            }
            inputStream.close();
            JSONObject xmlJSONObj = XML.toJSONObject(stringBuilder.toString());
            configs = new StopsConfigurations(xmlJSONObj);
        }
    } catch (IOException e) {
        Log.e("WorkOrder activity", "Can not read file: " + e.toString());
    } catch (JSONException e) {
        Log.e("WorkOrder activity", "Can not parse XML to JSON: " + e.toString());
    }
}
Example 50
Project: XSDInferencer-master  File: JSONTypesExtractorImpl.java View source code
/**
	 * Method that performs the conversion between JSON and XML
	 * @param jsonRoot the root of the JSON document. It must be either a {@link JSONObject} or a {@link JSONArray}
	 * @param namespaceRoot the namespace of the resulting root element
	 * @return a JDOM2 {@link Document} representing the obtained XML.
	 * @throws JDOMException
	 * @throws IOException
	 */
protected Document convertJSONToXML(Object jsonRoot, Namespace namespaceRoot) throws JDOMException, IOException {
    if (!(jsonRoot instanceof JSONArray || jsonRoot instanceof JSONObject)) {
        throw new IllegalArgumentException("'jsonRoot' must be either a JSONObject or a JSONArray");
    }
    quoteStringsAtJSON(jsonRoot);
    addPrefixToJSONKeysEndingsRecursive(jsonRoot, XSDInferenceConfiguration.ARRAY_ELEMENT_NAME, XSDInferenceConfiguration.ARRAY_ELEMENT_ESCAPING_PREFIX);
    encapsulateArraysAtJSONRecursive(jsonRoot);
    String xmlString = "<" + XSDInferenceConfiguration.XML_ROOT_NAME + ">" + XML.toString(jsonRoot) + "</" + XSDInferenceConfiguration.XML_ROOT_NAME + ">";
    SAXBuilder saxBuilder = new SAXBuilder();
    Document xmlDocument = saxBuilder.build(new StringReader(xmlString));
    setNamespaceToElementsByName(XSDInferenceConfiguration.ARRAY_ELEMENT_NAME, xmlDocument.getRootElement(), XSDInferenceConfiguration.NAMESPACE_ARRAY_ELEMENT);
    removePrefixToElementNameEndings(xmlDocument.getRootElement(), XSDInferenceConfiguration.ARRAY_ELEMENT_NAME, XSDInferenceConfiguration.ARRAY_ELEMENT_ESCAPING_PREFIX);
    xmlDocument.getRootElement().setNamespace(namespaceRoot);
    sortElementsRecursive(xmlDocument.getRootElement());
    return xmlDocument;
}
Example 51
Project: cas-overlay-master  File: OpenScienceFrameworkPrincipalFromRequestRemoteUserNonInteractiveCredentialsAction.java View source code
/**
     * Normalize the Remote Principal credential.
     *
     * @param credential the credential object bearing the username, password, etc...
     * @return the json object to serialize for authorization with the OSF API
     * @throws ParserConfigurationException a parser configuration exception
     * @throws TransformerException a transformer exception
     */
private JSONObject normalizeRemotePrincipal(final OpenScienceFrameworkCredential credential) throws ParserConfigurationException, TransformerException {
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document document = builder.newDocument();
    final Element rootElement = document.createElement("auth");
    document.appendChild(rootElement);
    // Add a custom attribute for Delegation-Protocol to the transformation
    final Element delegationProtocolAttr = document.createElement("attribute");
    delegationProtocolAttr.setAttribute("name", "Delegation-Protocol");
    delegationProtocolAttr.setAttribute("value", credential.getDelegationProtocol().getId());
    rootElement.appendChild(delegationProtocolAttr);
    // Add delegated attributes to the transformation
    for (final String key : credential.getDelegationAttributes().keySet()) {
        final Element attribute = document.createElement("attribute");
        attribute.setAttribute("name", key);
        attribute.setAttribute("value", credential.getDelegationAttributes().get(key));
        rootElement.appendChild(attribute);
    }
    // run the auth document through the transformer
    final DOMSource source = new DOMSource(document);
    final StringWriter writer = new StringWriter();
    final StreamResult result = new StreamResult(writer);
    this.institutionsAuthTransformer.transform(source, result);
    // convert transformed xml to json
    return XML.toJSONObject(writer.getBuffer().toString());
}
Example 52
Project: Hphoto-master  File: ApiServlet.java View source code
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // get parameters from request
    request.setCharacterEncoding("UTF-8");
    // the query language
    String lang = request.getParameter("hl");
    String kind = request.getParameter("kind");
    String alt = request.getParameter("alt");
    String owner = request.getParameter("user");
    String feed = request.getParameter("feed");
    String albumid = request.getParameter("album");
    if (lang != null) {
        if (lang.indexOf('_') == -1) {
        //throw
        }
        String language = lang.substring(0, lang.indexOf('_'));
        String count = lang.substring(lang.indexOf('_') + 1);
    }
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc = factory.newDocumentBuilder().newDocument();
        Element rss = addNode(doc, doc, "rss");
        addAttribute(doc, rss, "version", "2.0");
        addAttribute(doc, rss, "xmlns:opensearch", (String) NS_MAP.get("opensearch"));
        addAttribute(doc, rss, "xmlns:atom", (String) NS_MAP.get("atom"));
        addAttribute(doc, rss, "xmlns:photo", (String) NS_MAP.get("photo"));
        addAttribute(doc, rss, "xmlns:media", (String) NS_MAP.get("media"));
        Element channel = addNode(doc, rss, "channel");
        if (kind.equals("album")) {
            addCategory(doc, channel, request);
        } else if (kind.equals("photo")) {
            addPhoto(doc, channel, request);
        } else {
            response.getOutputStream().println("Invalid paramenter.");
            return;
        }
        if (alt.equals("json")) {
            String value = null;
            try {
                value = org.json.XML.toJSONObject(doc.toString()).toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (value != null)
                response.getOutputStream().print(value);
            return;
        }
        // dump DOM tree
        DOMSource source = new DOMSource(doc);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty("indent", "yes");
        StreamResult result = new StreamResult(response.getOutputStream());
        response.setContentType("text/xml");
        transformer.transform(source, result);
    } catch (javax.xml.parsers.ParserConfigurationException e) {
        throw new ServletException(e);
    } catch (javax.xml.transform.TransformerException e) {
        throw new ServletException(e);
    }
}
Example 53
Project: solo-master  File: MetaWeblogAPI.java View source code
/**
     * MetaWeblog requests processing.
     *
     * @param request the specified http servlet request
     * @param response the specified http servlet response
     * @param context the specified http request context
     */
@RequestProcessing(value = "/apis/metaweblog", method = HTTPRequestMethod.POST)
public void metaWeblog(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) {
    final TextXMLRenderer renderer = new TextXMLRenderer();
    context.setRenderer(renderer);
    String responseContent = null;
    try {
        final ServletInputStream inputStream = request.getInputStream();
        final String xml = IOUtils.toString(inputStream, "UTF-8");
        final JSONObject requestJSONObject = XML.toJSONObject(xml);
        final JSONObject methodCall = requestJSONObject.getJSONObject(METHOD_CALL);
        final String methodName = methodCall.getString(METHOD_NAME);
        LOGGER.log(Level.INFO, "MetaWeblog[methodName={0}]", methodName);
        final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");
        if (METHOD_DELETE_POST.equals(methodName)) {
            // Removes the first argument "appkey"
            params.remove(0);
        }
        final String userEmail = params.getJSONObject(INDEX_USER_EMAIL).getJSONObject("value").getString("string");
        final JSONObject user = userQueryService.getUserByEmail(userEmail);
        if (null == user) {
            throw new Exception("No user[email=" + userEmail + "]");
        }
        final String userPwd = params.getJSONObject(INDEX_USER_PWD).getJSONObject("value").getString("string");
        if (!user.getString(User.USER_PASSWORD).equals(MD5.hash(userPwd))) {
            throw new Exception("Wrong password");
        }
        if (METHOD_GET_USERS_BLOGS.equals(methodName)) {
            responseContent = getUsersBlogs();
        } else if (METHOD_GET_CATEGORIES.equals(methodName)) {
            responseContent = getCategories();
        } else if (METHOD_GET_RECENT_POSTS.equals(methodName)) {
            final int numOfPosts = params.getJSONObject(INDEX_NUM_OF_POSTS).getJSONObject("value").getInt("int");
            responseContent = getRecentPosts(numOfPosts);
        } else if (METHOD_NEW_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            addArticle(article);
            final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<params><param><value><string>").append(article.getString(Keys.OBJECT_ID)).append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_GET_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value").getString("string");
            responseContent = getPost(postId);
        } else if (METHOD_EDIT_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value").getString("string");
            article.put(Keys.OBJECT_ID, postId);
            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            final JSONObject updateArticleRequest = new JSONObject();
            updateArticleRequest.put(Article.ARTICLE, article);
            articleMgmtService.updateArticle(updateArticleRequest);
            final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<params><param><value><string>").append(postId).append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_DELETE_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value").getString("string");
            articleMgmtService.removeArticle(postId);
            final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<params><param><value><boolean>").append(true).append("</boolean></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else {
            throw new UnsupportedOperationException("Unsupported method[name=" + methodName + "]");
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse>").append("<fault><value><struct>").append("<member><name>faultCode</name><value><int>500</int></value></member>").append("<member><name>faultString</name><value><string>").append(e.getMessage()).append("</string></value></member></struct></value></fault></methodResponse>");
        responseContent = stringBuilder.toString();
    }
    renderer.setContent(responseContent);
}
Example 54
Project: livecount_load_tester-master  File: TestJSONObject.java View source code
/**
     * Tests the multipleThings method.
     */
public void testMultipleThings() {
    try {
        jsonobject = new JSONObject("{foo: [true, false,9876543210,    0.0, 1.00000001,  1.000000000001, 1.00000000000000001," + " .00000000000000001, 2.00, 0.1, 2e100, -32,[],{}, \"string\"], " + "  to   : null, op : 'Good'," + "ten:10} postfix comment");
        jsonobject.put("String", "98.6");
        jsonobject.put("JSONObject", new JSONObject());
        jsonobject.put("JSONArray", new JSONArray());
        jsonobject.put("int", 57);
        jsonobject.put("double", 123456789012345678901234567890.);
        jsonobject.put("true", true);
        jsonobject.put("false", false);
        jsonobject.put("null", JSONObject.NULL);
        jsonobject.put("bool", "true");
        jsonobject.put("zero", -0.0);
        jsonobject.put("\\u2028", "
");
        jsonobject.put("\\u2029", "
");
        jsonarray = jsonobject.getJSONArray("foo");
        jsonarray.put(666);
        jsonarray.put(2001.99);
        jsonarray.put("so \"fine\".");
        jsonarray.put("so <fine>.");
        jsonarray.put(true);
        jsonarray.put(false);
        jsonarray.put(new JSONArray());
        jsonarray.put(new JSONObject());
        jsonobject.put("keys", JSONObject.getNames(jsonobject));
        assertEquals("{\n    \"to\": null,\n    \"ten\": 10,\n    \"JSONObject\": {},\n    \"JSONArray\": [],\n    \"op\": \"Good\",\n    \"keys\": [\n        \"to\",\n        \"ten\",\n        \"JSONObject\",\n        \"JSONArray\",\n        \"op\",\n        \"int\",\n        \"true\",\n        \"foo\",\n        \"zero\",\n        \"double\",\n        \"String\",\n        \"false\",\n        \"bool\",\n        \"\\\\u2028\",\n        \"\\\\u2029\",\n        \"null\"\n    ],\n    \"int\": 57,\n    \"true\": true,\n    \"foo\": [\n        true,\n        false,\n        9876543210,\n        0,\n        1.00000001,\n        1.000000000001,\n        1,\n        1.0E-17,\n        2,\n        0.1,\n        2.0E100,\n        -32,\n        [],\n        {},\n        \"string\",\n        666,\n        2001.99,\n        \"so \\\"fine\\\".\",\n        \"so <fine>.\",\n        true,\n        false,\n        [],\n        {}\n    ],\n    \"zero\": -0,\n    \"double\": 1.2345678901234568E29,\n    \"String\": \"98.6\",\n    \"false\": false,\n    \"bool\": \"true\",\n    \"\\\\u2028\": \"\\u2028\",\n    \"\\\\u2029\": \"\\u2029\",\n    \"null\": null\n}", jsonobject.toString(4));
        assertEquals("<to>null</to><ten>10</ten><JSONObject></JSONObject><op>Good</op><keys>to</keys><keys>ten</keys><keys>JSONObject</keys><keys>JSONArray</keys><keys>op</keys><keys>int</keys><keys>true</keys><keys>foo</keys><keys>zero</keys><keys>double</keys><keys>String</keys><keys>false</keys><keys>bool</keys><keys>\\u2028</keys><keys>\\u2029</keys><keys>null</keys><int>57</int><true>true</true><foo>true</foo><foo>false</foo><foo>9876543210</foo><foo>0.0</foo><foo>1.00000001</foo><foo>1.000000000001</foo><foo>1.0</foo><foo>1.0E-17</foo><foo>2.0</foo><foo>0.1</foo><foo>2.0E100</foo><foo>-32</foo><foo></foo><foo></foo><foo>string</foo><foo>666</foo><foo>2001.99</foo><foo>so "fine".</foo><foo>so <fine>.</foo><foo>true</foo><foo>false</foo><foo></foo><foo></foo><zero>-0.0</zero><double>1.2345678901234568E29</double><String>98.6</String><false>false</false><bool>true</bool><\\u2028>
</\\u2028><\\u2029>
</\\u2029><null>null</null>", XML.toString(jsonobject));
        assertEquals(98.6d, jsonobject.getDouble("String"), eps);
        assertTrue(jsonobject.getBoolean("bool"));
        assertEquals("[true,false,9876543210,0,1.00000001,1.000000000001,1,1.0E-17,2,0.1,2.0E100,-32,[],{},\"string\",666,2001.99,\"so \\\"fine\\\".\",\"so <fine>.\",true,false,[],{}]", jsonobject.getJSONArray("foo").toString());
        assertEquals("Good", jsonobject.getString("op"));
        assertEquals(10, jsonobject.getInt("ten"));
        assertFalse(jsonobject.optBoolean("oops"));
    } catch (JSONException e) {
        fail(e.toString());
    }
}
Example 55
Project: appinventor-sources-master  File: Web.java View source code
/**
   * Decodes the given XML string to produce a list structure. <tag>string</tag> decodes to
   * a list that contains a pair of tag and string.  More generally, if obj1, obj2, ...
   * are tag-delimited XML strings, then <tag>obj1 obj2 ...</tag> decodes to a list
   * that contains a pair whose first element is tag and whose second element is the
   * list of the decoded obj's, ordered alphabetically by tags.  Examples:
   * <foo>123</foo> decodes to a one-item list containing the pair (foo, 123)
   * <foo>1 2 3</foo> decodes to a one-item list containing the pair (foo,"1 2 3")
   * <a><foo>1 2 3</foo><bar>456</bar></a> decodes to a list containing the pair
   * (a,X) where X is a 2-item list that contains the pair (bar,123) and the pair (foo,"1 2 3").
   * If the sequence of obj's mixes tag-delimited and non-tag-delimited
   * items, then the non-tag-delimited items are pulled out of the sequence and wrapped
   * with a "content" tag.  For example, decoding <a><bar>456</bar>many<foo>1 2 3</foo>apples</a>
   * is similar to above, except that the list X is a 3-item list that contains the additional pair
   * whose first item is the string "content", and whose second item is the list (many, apples).
   * This method signals an error and returns the empty list if the result is not well-formed XML.
   *
   * @param jsonText the JSON text to decode
   * @return the decoded text
   */
// This method works by by first converting the XML to JSON and then decoding the JSON.
@SimpleFunction(description = "Decodes the given XML string to produce a list structure.  " + "See the App Inventor documentation on \"Other topics, notes, and details\" for information.")
public // HTML for the component documentation on the Web.  It's too long for a tooltip, anyway.
Object XMLTextDecode(String XmlText) {
    try {
        JSONObject json = XML.toJSONObject(XmlText);
        return JsonTextDecode(json.toString());
    } catch (JSONException e) {
        Log.e("Exception in XMLTextDecode", e.getMessage());
        form.dispatchErrorOccurredEvent(this, "XMLTextDecode", ErrorMessages.ERROR_WEB_JSON_TEXT_DECODE_FAILED, e.getMessage());
        return YailList.makeEmptyList();
    }
}
Example 56
Project: teiid-designer-master  File: TeiidRestImportSourcePage.java View source code
private void createFileTableViewer(Composite parent) {
    Table table = new Table(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.CHECK);
    table.setHeaderVisible(true);
    table.setLinesVisible(true);
    table.setLayout(new TableLayout());
    table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    this.fileViewer = new TableViewer(table);
    GridData gd = new GridData(GridData.FILL_BOTH);
    gd.heightHint = 160;
    gd.horizontalSpan = 3;
    this.fileViewer.getControl().setLayoutData(gd);
    fileContentProvider = new DataFolderContentProvider();
    this.fileViewer.setContentProvider(fileContentProvider);
    this.fileViewer.setLabelProvider(new FileSystemLabelProvider());
    // Check events can occur separate from selection events.
    // In this case move the selected node.
    // Also trigger selection of node in model.
    this.fileViewer.getTable().addSelectionListener(new SelectionListener() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            if (processingChecks) {
                return;
            }
            processingChecks = true;
            if (e.detail == SWT.CHECK) {
                TableItem tableItem = (TableItem) e.item;
                boolean wasChecked = tableItem.getChecked();
                if (tableItem.getData() instanceof File) {
                    fileViewer.getTable().setSelection(new TableItem[] { tableItem });
                    if (wasChecked) {
                        for (TableItem item : fileViewer.getTable().getItems()) {
                            if (item != tableItem) {
                                item.setChecked(false);
                            }
                        }
                    }
                    info.setDoProcessXml((File) tableItem.getData(), wasChecked);
                }
            }
            processingChecks = false;
            synchronizeUI();
            validatePage();
        }

        @Override
        public void widgetDefaultSelected(SelectionEvent e) {
        }
    });
    // create columns
    fileNameColumn = new TableViewerColumn(this.fileViewer, SWT.LEFT);
    if (this.info.getFileMode() == TeiidMetadataImportInfo.FILE_MODE_TEIID_XML_URL) {
        // getString("dataFileNameColumn")); //$NON-NLS-1$
        fileNameColumn.getColumn().setText("XML Data File URL");
    } else {
        //$NON-NLS-1$
        fileNameColumn.getColumn().setText(getString("xmlDataFileNameColumn"));
    }
    fileNameColumn.setLabelProvider(new DataFileContentColumnLabelProvider());
    fileNameColumn.getColumn().pack();
}
Example 57
Project: karuta-backend-master  File: RestServicePortfolio.java View source code
/**
	 *	Get a portfolio from uuid
	 *	GET /rest/api/portfolios/portfolio/{portfolio-id}
	 *	parameters:
	 *	- resources:
	 *	- files: if set with resource, return a zip file
	 *	- export: if set, return xml as a file download
	 *	return:
	 *	zip
	 *	as file download
	 *	content
	 *	<?xml version=\"1.0\" encoding=\"UTF-8\"?>
	 *	<portfolio code=\"0\" id=\""+portfolioUuid+"\" owner=\""+isOwner+"\"><version>4</version>
	 *		<asmRoot>
	 *			<asm*>
	 *				<metadata-wad></metadata-wad>
	 *				<metadata></metadata>
	 *				<metadata-epm></metadata-epm>
	 *				<asmResource xsi_type="nodeRes">
	 *				<asmResource xsi_type="context">
	 *				<asmResource xsi_type="SPECIFIC TYPE">
	 *			</asm*>
	 *		</asmRoot>
	 *	</portfolio>
	 **/
@Path("/portfolios/portfolio/{portfolio-id}")
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/zip", MediaType.APPLICATION_OCTET_STREAM })
public Object getPortfolio(@CookieParam("user") String user, @CookieParam("credential") String token, @QueryParam("group") int groupId, @PathParam("portfolio-id") String portfolioUuid, @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest, @HeaderParam("Accept") String accept, @QueryParam("user") Integer userId, @QueryParam("group") Integer group, @QueryParam("resources") String resource, @QueryParam("files") String files, @QueryParam("export") String export, @QueryParam("lang") String lang, @QueryParam("level") String cutoff) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);
    Connection c = null;
    Response response = null;
    try {
        c = SqlUtils.getConnection(servContext);
        String portfolio = dataProvider.getPortfolio(c, new MimeType("text/xml"), portfolioUuid, ui.userId, 0, this.label, resource, "", ui.subId, cutoff).toString();
        if ("faux".equals(portfolio)) {
            response = Response.status(403).build();
        }
        if (response == null) {
            /// Finding back code. Not really pretty
            Date time = new Date();
            SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HHmmss");
            String timeFormat = dt.format(time);
            Document doc = DomUtils.xmlString2Document(portfolio, new StringBuffer());
            NodeList codes = doc.getDocumentElement().getElementsByTagName("code");
            // Le premier c'est celui du root
            Node codenode = codes.item(0);
            String code = "";
            if (codenode != null)
                code = codenode.getTextContent();
            // Sanitize code
            code = code.replace("_", "");
            if (export != null) {
                response = Response.ok(portfolio).header("content-disposition", "attachment; filename = \"" + code + "-" + timeFormat + ".xml\"").build();
            } else if (resource != null && files != null) {
                //// Cas du renvoi d'un ZIP
                HttpSession session = httpServletRequest.getSession(true);
                File tempZip = getZipFile(portfolioUuid, portfolio, lang, doc, session);
                /// Return zip file
                RandomAccessFile f = new RandomAccessFile(tempZip.getAbsoluteFile(), "r");
                byte[] b = new byte[(int) f.length()];
                f.read(b);
                f.close();
                response = Response.ok(b, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition", "attachment; filename = \"" + code + "-" + timeFormat + ".zip").build();
                // Temp file cleanup
                tempZip.delete();
            } else {
                if (portfolio.equals("faux")) {
                    throw new RestWebApplicationException(Status.FORBIDDEN, "Vous n'avez pas les droits necessaires");
                }
                if (accept.equals(MediaType.APPLICATION_JSON)) {
                    portfolio = XML.toJSONObject(portfolio).toString();
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_JSON).build();
                } else
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_XML).build();
                logRestRequest(httpServletRequest, null, portfolio, Status.OK.getStatusCode());
            }
        }
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString());
    } catch (SQLException ex) {
        logRestRequest(httpServletRequest, null, "Portfolio " + portfolioUuid + " not found", Status.NOT_FOUND.getStatusCode());
        logger.info("Portfolio " + portfolioUuid + " not found");
        throw new RestWebApplicationException(Status.NOT_FOUND, "Portfolio " + portfolioUuid + " not found");
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + ex.getStackTrace(), Status.INTERNAL_SERVER_ERROR.getStatusCode());
        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        try {
            if (c != null)
                c.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return response;
}
Example 58
Project: nuxeo-distribution-master  File: NuxeoLauncher.java View source code
/**
     * @since 5.6
     */
protected static void initParserOptions() {
    if (launcherOptions == null) {
        launcherOptions = new Options();
        // help option
        OptionBuilder.withLongOpt(OPTION_HELP);
        OptionBuilder.withDescription(OPTION_HELP_DESC);
        launcherOptions.addOption(OptionBuilder.create("h"));
        // Quiet option
        OptionBuilder.withLongOpt(OPTION_QUIET);
        OptionBuilder.withDescription(OPTION_QUIET_DESC);
        launcherOptions.addOption(OptionBuilder.create("q"));
        // Debug option
        OptionBuilder.withLongOpt(OPTION_DEBUG);
        OptionBuilder.withDescription(OPTION_DEBUG_DESC);
        launcherOptions.addOption(OptionBuilder.create("d"));
        // Debug category option
        OptionBuilder.withDescription(OPTION_DEBUG_CATEGORY_DESC);
        OptionBuilder.hasArg();
        launcherOptions.addOption(OptionBuilder.create(OPTION_DEBUG_CATEGORY));
        // Instance CLID option
        OptionBuilder.withLongOpt(OPTION_CLID);
        OptionBuilder.withDescription(OPTION_CLID_DESC);
        OptionBuilder.hasArg();
        launcherOptions.addOption(OptionBuilder.create());
        OptionGroup outputOptions = new OptionGroup();
        // Hide deprecation warnings option
        OptionBuilder.withLongOpt(OPTION_HIDE_DEPRECATION);
        OptionBuilder.withDescription(OPTION_HIDE_DEPRECATION_DESC);
        outputOptions.addOption(OptionBuilder.create());
        // XML option
        OptionBuilder.withLongOpt(OPTION_XML);
        OptionBuilder.withDescription(OPTION_XML_DESC);
        outputOptions.addOption(OptionBuilder.create());
        // JSON option
        OptionBuilder.withLongOpt(OPTION_JSON);
        OptionBuilder.withDescription(OPTION_JSON_DESC);
        outputOptions.addOption(OptionBuilder.create());
        launcherOptions.addOptionGroup(outputOptions);
        // GUI option
        OptionBuilder.withLongOpt(OPTION_GUI);
        OptionBuilder.hasArg();
        OptionBuilder.withArgName("true|false|yes|no");
        OptionBuilder.withDescription(OPTION_GUI_DESC);
        launcherOptions.addOption(OptionBuilder.create());
        // Package management option
        OptionBuilder.withLongOpt(OPTION_NODEPS);
        OptionBuilder.withDescription(OPTION_NODEPS_DESC);
        launcherOptions.addOption(OptionBuilder.create());
        // Relax on target platform option
        OptionBuilder.withLongOpt(OPTION_RELAX);
        OptionBuilder.hasArg();
        OptionBuilder.withArgName("true|false|yes|no|ask");
        OptionBuilder.withDescription(OPTION_RELAX_DESC);
        launcherOptions.addOption(OptionBuilder.create());
        // Accept option
        OptionBuilder.withLongOpt(OPTION_ACCEPT);
        OptionBuilder.hasArg();
        OptionBuilder.withArgName("true|false|yes|no|ask");
        OptionBuilder.withDescription(OPTION_ACCEPT_DESC);
        launcherOptions.addOption(OptionBuilder.create());
        // Allow SNAPSHOT option
        OptionBuilder.withLongOpt(OPTION_SNAPSHOT);
        OptionBuilder.withDescription(OPTION_SNAPSHOT_DESC);
        launcherOptions.addOption(OptionBuilder.create("s"));
        // Force option
        OptionBuilder.withLongOpt(OPTION_FORCE);
        OptionBuilder.withDescription(OPTION_FORCE_DESC);
        launcherOptions.addOption(OptionBuilder.create("f"));
        // Ignore missing option
        OptionBuilder.withLongOpt(OPTION_IGNORE_MISSING);
        OptionBuilder.withDescription(OPTION_IGNORE_MISSING_DESC);
        launcherOptions.addOption(OptionBuilder.create());
    }
}
Example 59
Project: open-wechat-sdk-master  File: Xml2JavaBean.java View source code
/**
	 * 
	 * @param xml
	 * @param Object
	 * @return
	 */
public static Object convert2JavaBean(String xml, Class<?> c) {
    //		logger.debug(xml);
    JSONObject xmlJSONObj = XML.toJSONObject(xml);
    JSONObject sub = (JSONObject) xmlJSONObj.get("xml");
    return JSON.parseObject(sub.toString(), c);
}
Example 60
Project: fi-smp-master  File: VerifiedReport.java View source code
public void setReport(String report) {
    //System.out.println(report);
    JSONObject json = XML.toJSONObject(report);
    //System.out.println(json.toString());
    this.report = json.toString();
}
Example 61
Project: AndroidRivers-master  File: XmlUtils.java View source code
private static JSONObject xml2json(String xml) {
    try {
        return XML.toJSONObject(xml);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Example 62
Project: SlipStreamServer-master  File: RunResource.java View source code
@Get("json")
public Representation toJson() throws NotFoundException, ValidationException, ConfigurationException {
    String xml = toXmlString();
    JSONObject obj = XML.toJSONObject(xml);
    return new StringRepresentation(obj.toString(), MediaType.APPLICATION_JSON);
}
Example 63
Project: DataHubSystem-master  File: SearchController.java View source code
/**
    * Converts input xml stream into output json stream.
    * WARNING this implementation stores xml data into memory.
    * <p>
    * @param xml_stream
    * @param output
    * @throws IOException
    * @throws JSONException
    */
void toJSON(InputStream xml_stream, OutputStream output) throws IOException, JSONException {
    StringWriter writer = new StringWriter();
    IOUtils.copy(xml_stream, writer, "UTF-8");
    JSONObject xmlJSONObj = XML.toJSONObject(writer.toString().trim());
    String jsonPrettyPrintString = xmlJSONObj.toString(3);
    output.write(jsonPrettyPrintString.getBytes());
}
Example 64
Project: pack-master  File: CrawlerPack.java View source code
/**
     * 將 json 轉為 XML
     *
     * @param json a json format string.
     * @return XML format string
     */
public String jsonToXml(String json) {
    String xml = "";
    // 處�直接以陣列開頭的JSON,並指定給予 row 的 tag
    if ("[".equals(json.substring(0, 1))) {
        xml = XML.toString(new JSONArray(json), "row");
    } else {
        xml = XML.toString(new JSONObject(json));
    }
    return xml;
}
Example 65
Project: vco-powershel-plugin-master  File: RemotePSObject.java View source code
@VsoMethod(description = "Returns the object as String that is XML formated")
public String getXml() {
    return xml;
}
Example 66
Project: tika-master  File: TEIParser.java View source code
public Metadata parse(String source) {
    JSONObject obj = XML.toJSONObject(source);
    Metadata metadata = new Metadata();
    createGrobidMetadata(source, obj, metadata);
    return metadata;
}