Example usage for java.io StringReader StringReader

List of usage examples for java.io StringReader StringReader

Introduction

In this page you can find the example usage for java.io StringReader StringReader.

Prototype

public StringReader(String s) 

Source Link

Document

Creates a new string reader.

Usage

From source file:org.opengeo.gsr.validation.JSONValidator.java

public static boolean isValidSchema(String json, File schemaFile) {
    boolean isValid = false;
    final String baseURI = "file:///" + schemaFile.getAbsolutePath();

    JsonSchema schema;/*from w w  w  .  ja  v a  2s  . c  o m*/
    try {
        JsonSchemaFactory factory = JsonSchemaFactory.newBuilder()
                .setLoadingConfiguration(LoadingConfiguration.newBuilder().setNamespace(baseURI).freeze())
                .freeze();
        JsonNode rawSchema = JsonLoader.fromFile(schemaFile);
        schema = factory.getJsonSchema(rawSchema);
    } catch (Exception e) {
        throw new RuntimeException("Failed to load JSON Schema from " + baseURI, e);
    }

    JsonNode jsonNode;
    try {
        Reader reader = new StringReader(json);
        jsonNode = JsonLoader.fromReader(reader);
    } catch (Exception e) {
        throw new RuntimeException("Couldn't load (" + json + ") as JSON", e);
    }

    ProcessingReport report;
    try {
        report = schema.validate(jsonNode);
    } catch (ProcessingException e) {
        e.printStackTrace();
        return false;
    }

    isValid = report.isSuccess();
    if (!isValid) {
        System.out.println("ERROR validating Json Schema in " + schemaFile);
        for (ProcessingMessage msg : report) {
            System.out.println(msg);
        }
    }
    return isValid;
}

From source file:Main.java

/**
 * /*  w w  w.jav a2s  . c  om*/
 * @param header Just a title for the stanza for readability.  Single word no spaces since
 * it is inserted as the root element in the output.
 * @param xml The string to pretty print
 */
static public void prettyPrint(String header, String xml) {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");

        if (header != null) {
            xml = "\n<" + header + ">" + xml + "</" + header + '>';
        }
        transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(System.out));
    } catch (Exception e) {
        System.out.println("Something wrong with xml in \n---------------\n" + xml + "\n---------------");
        e.printStackTrace();
    }
}

From source file:Main.java

public static Document string2Dom(final String fileContent)
        throws SAXException, IOException, ParserConfigurationException {
    return DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new InputSource(new StringReader(fileContent)));
}

From source file:net.sf.cb2xml.convert.MainframeToXml.java

private static String stripNullChars(String in) {
    try {/*from www. j  av  a 2 s  . c o  m*/
        Reader reader = new BufferedReader(new StringReader(in));
        StringBuffer buffer = new StringBuffer();
        int ch;
        while ((ch = reader.read()) > -1) {
            if (ch != 0) {
                buffer.append((char) ch);
            } else {
                buffer.append(' ');
            }
        }
        reader.close();
        return buffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.XStreamTools.java

public static Object fromXML(String xml) throws IOException {
    XStream xStream = getXStream();//from  ww  w.  j a  va 2s  . c o m
    return xStream.fromXML(new StringReader(xml));
}

From source file:com.thoughtworks.go.security.Registration.java

public static Registration fromJson(String json) {
    Map map = new Gson().fromJson(json, Map.class);
    List<Certificate> chain = new ArrayList<>();
    try {/* w w w . jav  a 2  s .c  om*/
        PemReader reader = new PemReader(new StringReader((String) map.get("agentPrivateKey")));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(reader.readPemObject().getContent());
        PrivateKey privateKey = kf.generatePrivate(spec);
        String agentCertificate = (String) map.get("agentCertificate");
        PemReader certReader = new PemReader(new StringReader(agentCertificate));
        while (true) {
            PemObject obj = certReader.readPemObject();
            if (obj == null) {
                break;
            }
            chain.add(CertificateFactory.getInstance("X.509")
                    .generateCertificate(new ByteArrayInputStream(obj.getContent())));
        }
        return new Registration(privateKey, chain.toArray(new Certificate[chain.size()]));
    } catch (IOException | NoSuchAlgorithmException | CertificateException | InvalidKeySpecException e) {
        throw bomb(e);
    }
}

From source file:Main.java

public static String findInXml(String xml, String xpath) {
    try {/*from  ww w .j a  va 2  s. c  om*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                //                    if (systemId.contains("foo.dtd")) {
                return new InputSource(new StringReader(""));
                //                    } else {
                //                        return null;
                //                    }
            }
        });
        Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPathExpression expr = xPathfactory.newXPath().compile(xpath);
        return (String) expr.evaluate(doc, XPathConstants.STRING);
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:Main.java

/**
 * //from  ww w  . ja v a2s.  c om
 * <B>Purpose:</B> Parses the String to an XML Document Object
 * 
 * @param xml
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static Document parse(String xml) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new InputSource(new StringReader(xml)));

}

From source file:com.soa.facepond.util.JsonUtil.java

/**
 * Convert JackSon string to Map<String, String>[].
 *
 * @param str - Jackson string/*ww w.  j a  v  a 2  s.c  om*/
 * @return Map<String, String>[]
 */
@SuppressWarnings("unchecked")
public static List<Map<String, String>> getListFromJsonArray(String str) {
    try {
        if (str != null && str.length() > 0) {
            ArrayList<Map<String, String>> arrList = (ArrayList<Map<String, String>>) new ObjectMapper()
                    .readValue(jf.createJsonParser(new StringReader(str)), List.class);
            return arrList;
        } else {
            log.warn("JacksonUtil.getListsFromJsonArray error| ErrMsg: input string is null ");
            return null;
        }
    } catch (Exception e) {
        log.error("JacksonUtil.getListsFromJsonArray error| ErrMsg: " + e.getMessage());
        return null;
    }

}

From source file:Main.java

public static Document stringToDom(String xmlSource)
        throws SAXException, ParserConfigurationException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(new InputSource(new StringReader(xmlSource)));
}