Example usage for java.io CharArrayReader CharArrayReader

List of usage examples for java.io CharArrayReader CharArrayReader

Introduction

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

Prototype

public CharArrayReader(char buf[]) 

Source Link

Document

Creates a CharArrayReader from the specified array of chars.

Usage

From source file:org.alder.fotobuchconvert.scribus.RtfToScribusConverter.java

public void convert(XmlBuilder xml, String input, ScribusWriter scribus)
        throws IOException, BadLocationException {
    if (input == null)
        return;/*from  w  w  w  .j  a va 2s. com*/

    log.debug("RTF input: " + input);

    CharArrayReader rd = new CharArrayReader(input.toCharArray());

    RTFEditorKit kit = new RTFEditorKit();
    DefaultStyledDocument doc = (DefaultStyledDocument) kit.createDefaultDocument();
    kit.read(rd, doc, 0);

    output(xml, doc, scribus);
}

From source file:net.mindengine.oculus.frontend.domain.document.testcase.Testcase.java

public static Testcase parse(String xmlData) throws Exception {
    Testcase testcase = new Testcase();

    try {//from  w  w  w . j  a v a2  s .  c  om
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = dbf.newDocumentBuilder();

        Reader reader = new CharArrayReader(xmlData.toCharArray());
        org.w3c.dom.Document doc = builder.parse(new org.xml.sax.InputSource(reader));

        Node root = doc.getDocumentElement();

        NodeList nodeList = root.getChildNodes();

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if ("steps".equals(node.getNodeName())) {
                NodeList stepsList = node.getChildNodes();
                for (int j = 0; j < stepsList.getLength(); j++) {
                    Node n = stepsList.item(j);

                    TestcaseStep step = new TestcaseStep();
                    step.setAction(XmlUtils.getChildNodeText(n, "action"));
                    step.setExpected(XmlUtils.getChildNodeText(n, "expected"));
                    step.setComment(XmlUtils.getChildNodeText(n, "comment"));
                    testcase.steps.add(step);
                }
            }
        }
    } catch (Exception e) {
    }

    return testcase;
}

From source file:com.pnf.plugin.pdf.XFAParser.java

public void parse(byte[] xmlContent) throws ParserConfigurationException, SAXException, IOException {
    CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
    decoder.onMalformedInput(CodingErrorAction.REPLACE);
    decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
    CharBuffer parsed = decoder.decode(ByteBuffer.wrap(xmlContent));

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();

    try (@SuppressWarnings("deprecation")
    InputStream is = new ReaderInputStream(new CharArrayReader(parsed.array()))) {
        parser.parse(is, xfa);/*from ww w.  ja  va  2s .  co m*/
    } catch (Exception e) {
        logger.catching(e);
        logger.error("Error while parsing XFA content");
    }
}

From source file:org.codehaus.mojo.license.utils.HttpRequester.java

/**
 * will download a external resource and read the content of the file that will then be translated into a
 * new list. <br>//from   ww  w . j av a  2 s. c  om
 * Lines starting with the character '#' will be omitted from the list <br>
 * <br>
 * <b>NOTE:</b><br>
 * certificate checking for this request will be disabled because some resources might be present on some
 * local servers in the internal network that do not use a safe connection
 *
 * @param url the URL to the external resource
 * @return a new list with all license entries from the remote resource
 */
public static List<String> downloadList(String url) throws MojoExecutionException {
    List<String> list = new ArrayList<>();
    BufferedReader bufferedReader = null;
    try {
        bufferedReader = new BufferedReader(new CharArrayReader(getFromUrl(url).toCharArray()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            if (StringUtils.isNotBlank(line)) {
                if (!StringUtils.startsWith(line, "#") && !list.contains(line)) {
                    list.add(line);
                }
            }
        }
    } catch (IOException e) {
        throw new MojoExecutionException("could not open connection to URL: " + url, e);
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        }
    }
    return list;
}

From source file:com.mirth.connect.plugins.datatypes.hl7v2.HL7v2ResponseValidator.java

@Override
public Response validate(Response response, ConnectorMessage connectorMessage) {
    HL7v2ResponseValidationProperties responseValidationProperties = getReplacedResponseValidationProperties(
            connectorMessage);/*  ww w .j a  v  a 2 s  .  c  o m*/
    String[] successfulACKCodes = StringUtils.split(responseValidationProperties.getSuccessfulACKCode(), ',');
    String[] errorACKCodes = StringUtils.split(responseValidationProperties.getErrorACKCode(), ',');
    String[] rejectedACKCodes = StringUtils.split(responseValidationProperties.getRejectedACKCode(), ',');
    boolean validateMessageControlId = responseValidationProperties.isValidateMessageControlId();

    String responseData = response.getMessage();

    if (StringUtils.isNotBlank(responseData)) {
        try {
            if (responseData.trim().startsWith("<")) {
                // XML response received
                Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .parse(new InputSource(new CharArrayReader(responseData.toCharArray())));
                String ackCode = XPathFactory.newInstance().newXPath().compile("//MSA.1/text()").evaluate(doc)
                        .trim();

                boolean rejected = Arrays.asList(rejectedACKCodes).contains(ackCode);
                boolean error = rejected || Arrays.asList(errorACKCodes).contains(ackCode);

                if (error || rejected) {
                    String msa3 = StringUtils.trim(
                            XPathFactory.newInstance().newXPath().compile("//MSA.3/text()").evaluate(doc));
                    String err1 = StringUtils.trim(
                            XPathFactory.newInstance().newXPath().compile("//ERR.1/text()").evaluate(doc));
                    handleNACK(response, rejected, msa3, err1);
                } else if (Arrays.asList(successfulACKCodes).contains(ackCode)) {
                    if (validateMessageControlId) {
                        String msa2 = StringUtils.trim(
                                XPathFactory.newInstance().newXPath().compile("//MSA.2/text()").evaluate(doc));
                        String originalControlID = getOriginalControlId(connectorMessage);

                        if (!StringUtils.equals(msa2, originalControlID)) {
                            handleInvalidControlId(response, originalControlID, msa2);
                        } else {
                            response.setStatus(Status.SENT);
                        }
                    } else {
                        response.setStatus(Status.SENT);
                    }
                }
            } else {
                // ER7 response received
                if (serializationProperties.isConvertLineBreaks()) {
                    responseData = StringUtil.convertLineBreaks(responseData, serializationSegmentDelimiter);
                }

                int index = -1;
                boolean valid = true;

                // Attempt to find the MSA segment using the segment delimiters in the serialization properties
                if ((index = responseData.indexOf(serializationSegmentDelimiter + "MSA")) >= 0) {
                    // MSA found; add the length of the segment delimiter, MSA, and field separator to get to the index of MSA.1
                    index += serializationSegmentDelimiter.length() + 4;

                    if (index < responseData.length()) {
                        boolean rejected = startsWithAny(responseData, rejectedACKCodes, index);
                        boolean error = rejected || startsWithAny(responseData, errorACKCodes, index);

                        char fieldSeparator = responseData.charAt(index - 1);
                        if (error || rejected) {
                            String msa3 = null;
                            String err1 = null;

                            // Index of MSA.2
                            index = responseData.indexOf(fieldSeparator, index);
                            if (index >= 0) {
                                // Index of MSA.3
                                index = responseData.indexOf(fieldSeparator, index + 1);
                                if (index >= 0) {
                                    // Find the next index of either the field separator or segment delimiter, and then the resulting substring
                                    String tempSegment = StringUtils.substring(responseData, index + 1);
                                    index = StringUtils.indexOfAny(tempSegment,
                                            fieldSeparator + serializationSegmentDelimiter);

                                    if (index >= 0) {
                                        msa3 = StringUtils.substring(tempSegment, 0, index);
                                    } else {
                                        msa3 = StringUtils.substring(tempSegment, 0);
                                    }
                                }
                            }

                            if ((index = responseData.indexOf(serializationSegmentDelimiter + "ERR")) >= 0) {
                                // ERR found; add the length of the segment delimiter, ERR, and field separator to get to the index of ERR.1
                                index += serializationSegmentDelimiter.length() + 4;
                                // Find the next index of either the field separator or segment delimiter, and then the resulting substring
                                String tempSegment = StringUtils.substring(responseData, index);
                                index = StringUtils.indexOfAny(tempSegment,
                                        fieldSeparator + serializationSegmentDelimiter);

                                if (index >= 0) {
                                    err1 = StringUtils.substring(tempSegment, 0, index);
                                } else {
                                    err1 = StringUtils.substring(tempSegment, 0);
                                }
                            }

                            handleNACK(response, rejected, msa3, err1);
                        } else if (startsWithAny(responseData, successfulACKCodes, index)) {
                            if (validateMessageControlId) {
                                String msa2 = "";
                                index = responseData.indexOf(fieldSeparator, index);

                                if (index >= 0) {
                                    String tempSegment = StringUtils.substring(responseData, index + 1);
                                    index = StringUtils.indexOfAny(tempSegment,
                                            fieldSeparator + serializationSegmentDelimiter);

                                    if (index >= 0) {
                                        msa2 = StringUtils.substring(tempSegment, 0, index);
                                    } else {
                                        msa2 = StringUtils.substring(tempSegment, 0);
                                    }
                                }
                                String originalControlID = getOriginalControlId(connectorMessage);

                                if (!StringUtils.equals(msa2, originalControlID)) {
                                    handleInvalidControlId(response, originalControlID, msa2);
                                } else {
                                    response.setStatus(Status.SENT);
                                }
                            } else {
                                response.setStatus(Status.SENT);
                            }
                        } else {
                            valid = false;
                        }
                    } else {
                        valid = false;
                    }
                } else {
                    valid = false;
                }

                if (!valid) {
                    response.setStatus(Status.QUEUED);
                    response.setStatusMessage("Invalid HL7 v2.x acknowledgement received.");
                    response.setError(response.getStatusMessage());
                }
            }
        } catch (Exception e) {
            response.setStatus(Status.QUEUED);
            response.setStatusMessage("Error validating response: " + e.getMessage());
            response.setError(ErrorMessageBuilder.buildErrorMessage(this.getClass().getSimpleName(),
                    response.getStatusMessage(), e));
        }
    } else {
        response.setStatus(Status.QUEUED);
        response.setStatusMessage("Empty or blank response received.");
        response.setError(response.getStatusMessage());
    }

    return response;
}

From source file:importer.handler.post.stages.SAXSplitter.java

/**
 * Split a TEI-XML file into versions of XML
 * @param tei the TEI content containing versions
 * @return an analysis of the variant markup in a file
 * @throws ImportException if something went wrong
 *//*from   w w w.j  a v a2 s  . c o  m*/
public JSONArray scan(String tei) throws ImporterException {
    this.layers = new HashMap<String, Integer>();
    this.lineNo = 1;
    this.splits = new HashSet<String>();
    this.attributes = new HashMap<String, String>();
    this.siblings = new HashMap<String, String>();
    this.states = new Stack<Integer>();
    this.states.push(0);
    this.siblingCount = 0;
    this.path = new StringBuilder();
    // hard-wire config for now
    attributes.put("add", "n");
    attributes.put("rdg", "wit");
    attributes.put("lem", "wit");
    siblings.put("add", "del");
    siblings.put("del", "add");
    siblings.put("lem", "rdg");
    siblings.put("rdg", "lem");
    splits.add("add");
    splits.add("del");
    splits.add("sic");
    splits.add("corr");
    splits.add("abbrev");
    splits.add("expan");
    splits.add("rdg");
    splits.add("lem");
    splits.add("app");
    splits.add("mod");
    splits.add("choice");
    splits.add("subst");
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        parser = spf.newSAXParser();
        xmlReader = parser.getXMLReader();
        xmlReader.setContentHandler(this);
        xmlReader.setErrorHandler(new MyErrorHandler(System.err));
        CharArrayReader car = new CharArrayReader(tei.toCharArray());
        xmlReader.parse(new InputSource(car));
        return layersToJson();
    } catch (Exception e) {
        throw new ImporterException(e);
    }
}

From source file:importer.handler.post.annotate.HTMLConverter.java

/**
 * Turn XML note content for Harpur to HTML
 * @param xml the xml note//  ww  w  .j a  v a  2 s.  c om
 * @param config the JSON config to control the conversion
 * @return a HTML string
 */
String convert(String xml) throws HTMLException {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        HTMLConverter conv = new HTMLConverter(patterns);
        spf.setNamespaceAware(true);
        SAXParser parser = spf.newSAXParser();
        XMLReader xmlReader = parser.getXMLReader();
        xmlReader.setContentHandler(conv);
        xmlReader.setErrorHandler(new MyErrorHandler(System.err));
        CharArrayReader car = new CharArrayReader(xml.toCharArray());
        InputSource input = new InputSource(car);
        xmlReader.parse(input);
        return conv.body.toString();
    } catch (Exception e) {
        throw new HTMLException(e);
    }
}

From source file:org.sakaiproject.search.component.adapter.contenthosting.XLContentDigester.java

public Reader getContentReader(ContentResource contentResource) {
    CharArrayWriter writer = new CharArrayWriter();
    loadContent(writer, contentResource);
    return new CharArrayReader(writer.toCharArray());
}

From source file:ext.services.xml.XMLUtils.java

/**
 * Return a DOM document for a given string <br>
 * In case of parsing error, this method handles the exception and null is
 * returned./*w  ww  .ja  v a  2s .  co m*/
 * 
 * @param xml the string to parse
 * 
 * @return a DOM document for a given string
 */
public static Document getDocument(String xml) {
    Document out = null;
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Reader reader = new CharArrayReader(xml.toCharArray());
        out = builder.parse(new InputSource(reader));
    } catch (Exception e) {
        // print first 500 characters of string that cannot be parsed...
        Log.debug("First 500 characters of XML: " + StringUtils.substring(xml, 0, 500));
        Log.error(e);
    }
    return out;
}

From source file:org.apache.hadoop.hive.serde2.OpenCSVSerde.java

@Override
public Object deserialize(final Writable blob) throws SerDeException {
    Text rowText = (Text) blob;

    CSVReader csv = null;/* ww w  .ja  v  a  2 s. co  m*/
    try {
        csv = newReader(new CharArrayReader(rowText.toString().toCharArray()), separatorChar, quoteChar,
                escapeChar);
        final String[] read = csv.readNext();

        for (int i = 0; i < numCols; i++) {
            if (read != null && i < read.length) {
                row.set(i, read[i]);
            } else {
                row.set(i, null);
            }
        }

        return row;
    } catch (final Exception e) {
        throw new SerDeException(e);
    } finally {
        if (csv != null) {
            try {
                csv.close();
            } catch (final Exception e) {
                LOG.error("fail to close csv writer ", e);
            }
        }
    }
}