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:com.mirth.connect.plugins.datatypes.hl7v2.HL7v2AutoResponder.java

private Response generateACK(Status status, String hl7Message,
        HL7v2ResponseGenerationProperties hl7v2Properties) throws Exception {
    boolean errorOnly = false;
    boolean always = false;
    boolean successOnly = false;

    hl7Message = hl7Message.trim();//from  ww w . jav  a 2  s  .  c om
    boolean isXML = StringUtils.isNotBlank(hl7Message) && hl7Message.charAt(0) == '<';

    String ACK = null;
    String statusMessage = null;
    String error = null;

    try {
        if (serializationProperties.isConvertLineBreaks() && !isXML) {
            hl7Message = StringUtil.convertLineBreaks(hl7Message, serializationSegmentDelimiter);
        }

        // Check if we have to look at MSH15     
        if (hl7v2Properties.isMsh15ACKAccept()) {
            // MSH15 Dictionary:
            // AL: Always
            // NE: Never
            // ER: Error / Reject condition
            // SU: Successful completion only

            String msh15 = "";

            // Check if the message is ER7 or XML
            if (isXML) { // XML form
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression msh15Query = xpath.compile("//MSH.15/text()");
                DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = domFactory.newDocumentBuilder();
                Reader reader = new CharArrayReader(hl7Message.toCharArray());
                Document doc = builder.parse(new InputSource(reader));
                msh15 = msh15Query.evaluate(doc);
            } else { // ER7
                char fieldDelim = hl7Message.charAt(3); // Usually |
                char componentDelim = hl7Message.charAt(4); // Usually ^

                Pattern fieldPattern = Pattern.compile(Pattern.quote(String.valueOf(fieldDelim)));
                Pattern componentPattern = Pattern.compile(Pattern.quote(String.valueOf(componentDelim)));

                String mshString = StringUtils.split(hl7Message, serializationSegmentDelimiter)[0];
                String[] mshFields = fieldPattern.split(mshString);

                if (mshFields.length > 14) {
                    msh15 = componentPattern.split(mshFields[14])[0]; // MSH.15.1
                }
            }

            if (msh15 != null && !msh15.equals("")) {
                if (msh15.equalsIgnoreCase("AL")) {
                    always = true;
                } else if (msh15.equalsIgnoreCase("NE")) {
                    logger.debug("MSH15 is NE, Skipping ACK");
                    return null;
                } else if (msh15.equalsIgnoreCase("ER")) {
                    errorOnly = true;
                } else if (msh15.equalsIgnoreCase("SU")) {
                    successOnly = true;
                }
            }
        }

        String ackCode = "AA";
        String ackMessage = "";
        boolean nack = false;

        if (status == Status.ERROR) {
            if (successOnly) {
                // we only send an ACK on success
                return null;
            }
            ackCode = hl7v2Properties.getErrorACKCode();
            ackMessage = hl7v2Properties.getErrorACKMessage();
            nack = true;
        } else if (status == Status.FILTERED) {
            if (successOnly) {
                return null;
            }
            ackCode = hl7v2Properties.getRejectedACKCode();
            ackMessage = hl7v2Properties.getRejectedACKMessage();
            nack = true;
        } else {
            if (errorOnly) {
                return null;
            }
            ackCode = hl7v2Properties.getSuccessfulACKCode();
            ackMessage = hl7v2Properties.getSuccessfulACKMessage();
        }

        ACK = HL7v2ACKGenerator.generateAckResponse(hl7Message, isXML, ackCode, ackMessage,
                generationProperties.getDateFormat(), new String(), deserializationSegmentDelimiter);
        statusMessage = "HL7v2 " + (nack ? "N" : "") + "ACK successfully generated.";
        logger.debug("HL7v2 " + (nack ? "N" : "") + "ACK successfully generated: " + ACK);
    } catch (Exception e) {
        logger.warn("Error generating HL7v2 ACK.", e);
        throw new Exception("Error generating HL7v2 ACK.", e);
    }

    return new Response(status, ACK, statusMessage, error);
}

From source file:org.onehippo.forge.hst.pdf.renderer.servlet.HtmlPDFRenderingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!(response instanceof HttpServletResponse)) {
        chain.doFilter(request, response);
        return;//  w w w. j  a va  2s . com
    }

    if (response.isCommitted()) {
        log.warn("The servlet response is already committed for the request: '{}'.",
                ((HttpServletRequest) request).getRequestURI());
        chain.doFilter(request, response);
        return;
    }

    ContentCapturingHttpServletResponse capturingResponse = null;
    InputStream htmlInputStream = null;
    Reader htmlReader = null;
    OutputStream pdfOutputStream = null;

    try {
        capturingResponse = new ContentCapturingHttpServletResponse((HttpServletResponse) response);
        chain.doFilter(request, capturingResponse);

        if (capturingResponse.isWrittenToPrintWriter()) {
            htmlReader = new CharArrayReader(capturingResponse.toCharArray());
        } else {
            htmlInputStream = new ByteArrayInputStream(capturingResponse.toByteArray());
            String characterEncoding = StringUtils.defaultIfBlank(capturingResponse.getCharacterEncoding(),
                    "UTF-8");
            htmlReader = new InputStreamReader(htmlInputStream, characterEncoding);
        }

        capturingResponse.close();
        capturingResponse = null;

        response.setContentType("application/pdf");

        StringBuilder headerValue = new StringBuilder("attachment");
        headerValue.append("; filename=\"").append(getDocumentFilename((HttpServletRequest) request))
                .append("\"");
        ((HttpServletResponse) response).addHeader("Content-Disposition", headerValue.toString());

        pdfOutputStream = response.getOutputStream();
        pdfRenderer.renderHtmlToPDF(htmlReader, true, pdfOutputStream,
                getDocumentURL((HttpServletRequest) request),
                getExternalLinkBaseURL((HttpServletRequest) request));
    } catch (Exception e) {

    } finally {
        if (capturingResponse != null) {
            capturingResponse.close();
        }

        IOUtils.closeQuietly(pdfOutputStream);
        IOUtils.closeQuietly(htmlReader);
        IOUtils.closeQuietly(htmlInputStream);
    }
}

From source file:org.openmrs.module.radiology.test.RadiologyTestData.java

/**
 * Convenience method constructing a complex obs for the tests
 *///www  .  ja  v  a2  s  .  c  o m
public static Obs getMockComplexObsAsHtmlViewForMockObs() {

    Obs mockObs = new Obs();
    Reader input = new CharArrayReader("<img src='/openmrs/complexObsServlet?obsId=1'/>".toCharArray());
    ComplexData complexData = new ComplexData("htmlView", input);
    mockObs.setComplexData(complexData);
    return mockObs;
}

From source file:net.ontopia.topicmaps.nav2.servlets.DataIntegrationServlet.java

public TopicMapIF transformRequest(String transformId, InputStream xmlstream, LocatorIF base) throws Exception {

    InputStream xsltstream = StreamUtils.getInputStream("classpath:" + transformId + ".xsl");
    if (xsltstream == null)
        throw new ServletException("Could not find style sheet '" + transformId + ".xsl'");

    // set up source and target streams
    // Source xmlSource = new StreamSource(xmlstream);
    Source xmlSource = new StreamSource(xmlstream);
    Source xsltSource = new StreamSource(xsltstream);

    // the factory pattern supports different XSLT processors
    TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = transFact.newTransformer(xsltSource);

    CharArrayWriter cw = new CharArrayWriter();
    trans.transform(xmlSource, new StreamResult(cw));
    CharArrayReader cr = new CharArrayReader(cw.toCharArray());

    TopicMapStoreIF store = new InMemoryTopicMapStore();
    TopicMapIF topicmap = store.getTopicMap();
    store.setBaseAddress(base);/*from w  w w . j av  a 2  s  . com*/
    XTMTopicMapReader xr = new XTMTopicMapReader(cr, base);
    xr.setValidation(false);
    xr.importInto(topicmap);

    return topicmap;
}

From source file:hm.binkley.util.XProperties.java

/**
 * Note {@code XProperties} description for additional features over plain
 * properties loading. {@inheritDoc}//w  ww  .ja  va 2 s  . c  o m
 *
 * @throws IOException if the properties cannot be loaded or if included
 * resources cannot be read
 */
@Override
public synchronized void load(@Nonnull final Reader reader) throws IOException {
    final ResourcePatternResolver loader = new PathMatchingResourcePatternResolver();
    try (final CharArrayWriter writer = new CharArrayWriter()) {
        try (final BufferedReader lines = new BufferedReader(reader)) {
            for (String line = lines.readLine(); null != line; line = lines.readLine()) {
                writer.append(line).append('\n');
                final Matcher matcher = include.matcher(line);
                if (matcher.matches())
                    for (final String x : comma.split(substitutor.replace(matcher.group(1))))
                        for (final Resource resource : loader.getResources(x)) {
                            final URI uri = resource.getURI();
                            if (!included.add(uri))
                                throw new RecursiveIncludeException(uri, included);
                            try (final InputStream in = resource.getInputStream()) {
                                load(in);
                            }
                        }
            }
        }

        super.load(new CharArrayReader(writer.toCharArray()));
    }
    included.clear();
}

From source file:org.openmrs.module.radiology.test.RadiologyTestData.java

/**
 * Convenience method constructing a complex obs for the tests
 *///from   www .j a  v  a2  s  .c o m
public static Obs getMockComplexObsAsHyperlinkViewForMockObs() {

    Obs mockObs = new Obs();
    Reader input = new CharArrayReader("openmrs/complexObsServlet?obsId=1".toCharArray());
    ComplexData complexData = new ComplexData("hyperlinkView", input);
    mockObs.setComplexData(complexData);
    return mockObs;
}

From source file:org.roda.core.common.RodaUtils.java

public static Reader applyMetadataStylesheet(Binary binary, String basePath, String metadataType,
        String metadataVersion, Map<String, String> parameters) throws GenericException {
    try (Reader descMetadataReader = new InputStreamReader(
            new BOMInputStream(binary.getContent().createInputStream()))) {

        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setEntityResolver(new RodaEntityResolver());
        InputSource source = new InputSource(descMetadataReader);
        Source text = new SAXSource(xmlReader, source);

        XsltExecutable xsltExecutable = CACHE.get(Triple.of(basePath, metadataType, metadataVersion));

        XsltTransformer transformer = xsltExecutable.load();
        CharArrayWriter transformerResult = new CharArrayWriter();

        transformer.setSource(text);//from   w w  w .j a v a 2  s  . c o  m
        transformer.setDestination(PROCESSOR.newSerializer(transformerResult));

        for (Entry<String, String> parameter : parameters.entrySet()) {
            QName qName = new QName(parameter.getKey());
            XdmValue xdmValue = new XdmAtomicValue(parameter.getValue());
            transformer.setParameter(qName, xdmValue);
        }

        transformer.transform();

        return new CharArrayReader(transformerResult.toCharArray());

    } catch (IOException | SAXException | ExecutionException | SaxonApiException e) {
        throw new GenericException("Could not process descriptive metadata binary " + binary.getStoragePath()
                + " metadata type " + metadataType + " and version " + metadataVersion, e);
    }
}

From source file:org.wso2.carbon.pc.core.extensions.aspects.ProcessLifeCycle.java

private void setSCXMLConfiguration(Registry registry)
        throws RegistryException, XMLStreamException, IOException, SAXException, ModelException {
    String xmlContent;//from w w  w .j av a 2 s .co m
    if (isConfigurationFromResource) {
        if (registry.resourceExists(configurationResourcePath)) {
            try {
                Resource configurationResource = registry.get(configurationResourcePath);
                xmlContent = RegistryUtils.decodeBytes((byte[]) configurationResource.getContent());
                configurationElement = AXIOMUtil.stringToOM(xmlContent);
                configurationElement.toString();
            } catch (Exception e) {
                String msg = "Invalid lifecycle configuration found at " + configurationResourcePath;
                log.error(msg, e);
                throw new RegistryException(msg);
            }
        } else {
            String msg = "Unable to find the lifecycle configuration from the given path: "
                    + configurationResourcePath;
            log.error(msg);
            throw new RegistryException(msg);
        }
    }

    try {
        if (configurationElement.getAttributeValue(new QName(LifecycleConstants.AUDIT)) != null) {
            isAuditEnabled = Boolean
                    .parseBoolean(configurationElement.getAttributeValue(new QName(LifecycleConstants.AUDIT)));
        }
        OMElement scxmlElement = configurationElement.getFirstElement();
        scxml = SCXMLParser.parse(new InputSource(new CharArrayReader((scxmlElement.toString()).toCharArray())),
                null);
    } catch (Exception e) {
        String msg = "Invalid SCXML configuration found";
        log.error(msg, e);
        throw new RegistryException(msg);
    }
}

From source file:de.suse.swamp.core.util.BugzillaTools.java

private synchronized void xmlToData(String url) throws Exception {

    HttpState initialState = new HttpState();

    String authUsername = swamp.getProperty("BUGZILLA_AUTH_USERNAME");
    String authPassword = swamp.getProperty("BUGZILLA_AUTH_PWD");

    if (authUsername != null && authUsername.length() != 0) {
        Credentials defaultcreds = new UsernamePasswordCredentials(authUsername, authPassword);
        initialState.setCredentials(AuthScope.ANY, defaultcreds);
    } else {// w w  w .  ja v a 2  s.c o  m
        Cookie[] cookies = getCookies();
        for (int i = 0; i < cookies.length; i++) {
            initialState.addCookie(cookies[i]);
            Logger.DEBUG("Added Cookie: " + cookies[i].getName() + "=" + cookies[i].getValue(), log);
        }
    }
    HttpClient httpclient = new HttpClient();
    httpclient.setState(initialState);
    HttpMethod httpget = new GetMethod(url);
    try {
        httpclient.executeMethod(httpget);
    } catch (Exception e) {
        throw new Exception("Could not get URL " + url);
    }

    String content = httpget.getResponseBodyAsString();
    char[] chars = content.toCharArray();

    // removing illegal characters from bugzilla output.
    for (int i = 0; i < chars.length; i++) {
        if (chars[i] < 32 && chars[i] != 9 && chars[i] != 10 && chars[i] != 13) {
            Logger.DEBUG("Removing illegal character: '" + chars[i] + "' on position " + i, log);
            chars[i] = ' ';
        }
    }
    Logger.DEBUG(String.valueOf(chars), log);
    CharArrayReader reader = new CharArrayReader(chars);
    XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    parser.setFeature("http://xml.org/sax/features/validation", false);
    // disable parsing of external dtd
    parser.setFeature("http://xml.org/sax/features/external-general-entities", false);
    parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    parser.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    // get XML File
    BugzillaReader handler = new BugzillaReader();
    parser.setContentHandler(handler);
    InputSource source = new InputSource();
    source.setCharacterStream(reader);
    source.setEncoding("utf-8");
    try {
        parser.parse(source);
    } catch (SAXParseException spe) {
        spe.printStackTrace();
        throw spe;
    }
    httpget.releaseConnection();
    if (errormsg != null) {
        throw new Exception(errormsg);
    }
}

From source file:org.wso2.carbon.governance.registry.extensions.aspects.DefaultLifeCycle.java

private void setSCXMLConfiguration(Registry registry)
        throws RegistryException, XMLStreamException, IOException, SAXException, ModelException {
    String xmlContent;/*from   w  w w. ja  v  a 2  s. c om*/
    if (isConfigurationFromResource) {
        if (registry.resourceExists(configurationResourcePath)) {
            try {
                Resource configurationResource = registry.get(configurationResourcePath);
                xmlContent = RegistryUtils.decodeBytes((byte[]) configurationResource.getContent());
                configurationElement = AXIOMUtil.stringToOM(xmlContent);
                // to validate XML
                configurationElement.toString();
            } catch (Exception e) {
                String msg = "Invalid lifecycle configuration found at " + configurationResourcePath;
                log.error(msg);
                throw new RegistryException(msg);
            }
        } else {
            String msg = "Unable to find the lifecycle configuration from the given path: "
                    + configurationResourcePath;
            log.error(msg);
            throw new RegistryException(msg);
        }
    }

    try {
        //            We check if there is an attribute called "audit" and if it exists, what is the value of that attribute
        if (configurationElement.getAttributeValue(new QName(LifecycleConstants.AUDIT)) != null) {
            isAuditEnabled = Boolean
                    .parseBoolean(configurationElement.getAttributeValue(new QName(LifecycleConstants.AUDIT)));
        }

        //            Here we are taking the scxml element from the configuration
        OMElement scxmlElement = configurationElement.getFirstElement();
        scxml = SCXMLParser.parse(new InputSource(new CharArrayReader((scxmlElement.toString()).toCharArray())),
                null);
    } catch (Exception e) {
        String msg = "Invalid SCXML configuration found";
        log.error(msg);
        throw new RegistryException(msg);
    }
}