List of usage examples for java.io CharArrayReader CharArrayReader
public CharArrayReader(char buf[])
From source file:org.wso2.carbon.governance.lcm.util.LifecycleBeanPopulator.java
public static boolean deserializeLifecycleBean(OMElement configurationElement, Registry registry) throws Exception { CommonUtil.validateOMContent(configurationElement, CommonUtil.getLifecycleSchemaValidator(CommonUtil.getLifecycleSchemaLocation())); try {/*from w ww. j a v a 2s .c o m*/ OMElement scxmlElement = null; OMElement lifecycleElement = null; OMElement configuration = configurationElement.getFirstElement(); String type = configuration.getAttributeValue(new QName("type")); if (type.equals("literal")) { lifecycleElement = configuration.getFirstElement(); } else if (type.equals("resource")) { String resourcePath = configuration.getText(); if (registry.resourceExists(resourcePath)) { Resource resource = registry.get(resourcePath); if (resource.getContent() != null) { if (resource.getContent() instanceof String) { lifecycleElement = CommonUtil.buildOMElement((String) resource.getContent()); } else if (resource.getContent() instanceof byte[]) { lifecycleElement = CommonUtil .buildOMElement(RegistryUtils.decodeBytes((byte[]) resource.getContent())); } else { String msg = "Could not find valid lifecycle configuration"; log.error(msg); throw new RegistryException(msg); } } else { String msg = "Resource does not contain a valid lifecycle configuration"; log.error(msg); throw new RegistryException(msg); } } else { String msg = "Resource not found at " + resourcePath; log.error(msg); throw new RegistryException(msg); } } else { String msg = "The type must be either literal or resource"; log.error(msg); throw new RegistryException(msg); } scxmlElement = lifecycleElement.getFirstElement(); CommonUtil.validateOMContent(scxmlElement); CommonUtil.validateLifeCycle(scxmlElement); // Validating whether this complies to the scxml specification. SCXMLParser.parse(new InputSource(new CharArrayReader((scxmlElement.toString()).toCharArray())), null); // Validating whether the data model is correct if (!CommonUtil.validateSCXMLDataModel(scxmlElement)) { throw new RegistryException("Failed to validate the data model. Invalid forEvent found"); } } catch (RegistryException e) { throw e; } catch (Exception e) { String msg = e.getMessage() + ". " + "Please check whether there are any whitespaces in state names"; log.error(msg, e); throw new RegistryException(msg); } return true; }
From source file:bamboo.openhash.fileshare.FileShare.java
public static void main(String[] args) throws Exception { PatternLayout pl = new PatternLayout("%d{ISO8601} %-5p %c: %m\n"); ConsoleAppender ca = new ConsoleAppender(pl); Logger.getRoot().addAppender(ca); Logger.getRoot().setLevel(Level.INFO); // create Options object Options options = new Options(); // add t option options.addOption("r", "read", false, "read a file from the DHT"); options.addOption("w", "write", false, "write a file to the DHT"); options.addOption("g", "gateway", true, "the gateway IP:port"); options.addOption("k", "key", true, "the key to read a file from"); options.addOption("f", "file", true, "the file to read or write"); options.addOption("s", "secret", true, "the secret used to hide data"); options.addOption("t", "ttl", true, "how long in seconds data should persist"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String gw = null;/* w w w .j a v a 2 s. c o m*/ String mode = null; String secret = null; String ttl = null; String key = null; String file = null; if (cmd.hasOption("r")) { mode = "read"; } if (cmd.hasOption("w")) { mode = "write"; } if (cmd.hasOption("g")) { gw = cmd.getOptionValue("g"); } if (cmd.hasOption("k")) { key = cmd.getOptionValue("k"); } if (cmd.hasOption("f")) { file = cmd.getOptionValue("f"); } if (cmd.hasOption("s")) { secret = cmd.getOptionValue("s"); } if (cmd.hasOption("t")) { ttl = cmd.getOptionValue("t"); } if (mode == null) { System.err.println("ERROR: either --read or --write is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } if (gw == null) { System.err.println("ERROR: --gateway is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } if (file == null) { System.err.println("ERROR: --file is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } if (secret == null) { System.err.println("ERROR: --secret is required"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } StringBuffer sbuf = new StringBuffer(1000); sbuf.append("<sandstorm>\n"); sbuf.append("<global>\n"); sbuf.append("<initargs>\n"); sbuf.append("node_id localhost:3630\n"); sbuf.append("</initargs>\n"); sbuf.append("</global>\n"); sbuf.append("<stages>\n"); sbuf.append("<GatewayClient>\n"); sbuf.append("class bamboo.dht.GatewayClient\n"); sbuf.append("<initargs>\n"); sbuf.append("debug_level 0\n"); sbuf.append("gateway " + gw + "\n"); sbuf.append("</initargs>\n"); sbuf.append("</GatewayClient>\n"); sbuf.append("\n"); sbuf.append("<FileShare>\n"); sbuf.append("class bamboo.openhash.fileshare.FileShare\n"); sbuf.append("<initargs>\n"); sbuf.append("debug_level 0\n"); sbuf.append("secret " + secret + "\n"); sbuf.append("mode " + mode + "\n"); if (mode.equals("write")) { if (ttl == null) { System.err.println("ERROR: --ttl is required for write mode"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } sbuf.append("ttl " + ttl + "\n"); sbuf.append("file " + file + "\n"); } else { if (key == null) { System.err.println("ERROR: --key is required for write mode"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fileshare", options); System.exit(1); } sbuf.append("key " + key + "\n"); sbuf.append("file " + file + "\n"); } sbuf.append("client_stage_name GatewayClient\n"); sbuf.append("</initargs>\n"); sbuf.append("</FileShare>\n"); sbuf.append("</stages>\n"); sbuf.append("</sandstorm>\n"); ASyncCore acore = new bamboo.lss.ASyncCoreImpl(); DustDevil dd = new DustDevil(); dd.set_acore_instance(acore); dd.main(new CharArrayReader(sbuf.toString().toCharArray())); acore.async_main(); }
From source file:org.roda.core.common.RodaUtils.java
public static Reader applyEventStylesheet(Binary binary, boolean onlyDetails, Map<String, String> translations, String path) 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 = EVENT_CACHE.get(path); XsltTransformer transformer = xsltExecutable.load(); CharArrayWriter transformerResult = new CharArrayWriter(); transformer.setSource(text);//from w ww .ja v a 2 s .c om transformer.setDestination(PROCESSOR.newSerializer(transformerResult)); // send param to filter stylesheet work transformer.setParameter(new QName("onlyDetails"), new XdmAtomicValue(Boolean.toString(onlyDetails))); for (Entry<String, String> parameter : translations.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) { LOGGER.error(e.getMessage(), e); throw new GenericException("Could not process event binary " + binary.getStoragePath(), e); } }
From source file:org.wso2.jaggery.scxml.aspects.JaggeryTravellingPermissionLifeCycle.java
private void setSCXMLConfiguration(Registry registry) throws RegistryException, XMLStreamException, IOException, SAXException, ModelException { String xmlContent;/*from w w w . j a v 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); } 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); } }
From source file:com.mirth.connect.plugins.datatypes.hl7v2.HL7v2ResponseValidator.java
private String getOriginalControlId(ConnectorMessage connectorMessage) throws Exception { String controlId = ""; String originalMessage = ""; if (responseValidationProperties.getOriginalMessageControlId() .equals(OriginalMessageControlId.Destination_Encoded)) { originalMessage = connectorMessage.getEncoded().getContent(); } else if (responseValidationProperties.getOriginalMessageControlId() .equals(OriginalMessageControlId.Map_Variable)) { String originalIdMapVariable = responseValidationProperties.getOriginalIdMapVariable(); if (StringUtils.isEmpty(originalIdMapVariable)) { throw new Exception("Map variable for original control Id not set."); }/*from www .j a va 2 s . c o m*/ Object value = null; if (connectorMessage.getConnectorMap().containsKey(originalIdMapVariable)) { value = connectorMessage.getConnectorMap().get(originalIdMapVariable); } else { value = connectorMessage.getChannelMap().get(originalIdMapVariable); } if (value == null) { throw new Exception("Map variable for original control Id not set."); } controlId = value.toString(); return controlId; } if (originalMessage.startsWith("<")) { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new CharArrayReader(originalMessage.toCharArray()))); controlId = XPathFactory.newInstance().newXPath().compile("//MSH.10.1/text()").evaluate(doc).trim(); } else { int index; if ((index = originalMessage.indexOf("MSH")) >= 0) { index += 4; char fieldSeparator = originalMessage.charAt(index - 1); int iteration = 2; int segmentDelimeterIndex = originalMessage.indexOf(serializationSegmentDelimiter, index); while (iteration < MESSAGE_CONTROL_ID_FIELD) { index = originalMessage.indexOf(fieldSeparator, index + 1); if ((segmentDelimeterIndex >= 0 && segmentDelimeterIndex < index) || index == -1) { return ""; } iteration++; } String tempSegment = StringUtils.substring(originalMessage, index + 1); index = StringUtils.indexOfAny(tempSegment, fieldSeparator + serializationSegmentDelimiter); if (index >= 0) { controlId = StringUtils.substring(tempSegment, 0, index); } else { controlId = StringUtils.substring(tempSegment, 0); } } } return controlId; }
From source file:com.redskyit.scriptDriver.RunTests.java
private StreamTokenizer openString(String code) { // StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(new ByteArrayInputStream(code.getBytes())))); StreamTokenizer tokenizer = new StreamTokenizer(new CharArrayReader(code.toCharArray())); initTokenizer(tokenizer);//w ww . java 2 s . c om return tokenizer; }
From source file:org.apache.lens.lib.query.CSVSerde.java
@Override public Object deserialize(final Writable blob) throws SerDeException { Text rowText = (Text) blob; CSVReader csv = null;/*from w ww . j av a2 s . c o 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 && !read[i].equals(nullString)) { row.set(i, getColumnObject(read[i], columnTypes.get(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) { // ignore } } } }
From source file:org.apache.nifi.processors.standard.util.TestJdbcCommon.java
@Test public void testClob() throws Exception { try (final Statement stmt = con.createStatement()) { stmt.executeUpdate("CREATE TABLE clobtest (id INT, text CLOB(64 K))"); stmt.execute("INSERT INTO blobtest VALUES (41, NULL)"); PreparedStatement ps = con.prepareStatement("INSERT INTO clobtest VALUES (?, ?)"); ps.setInt(1, 42);/*w w w.ja va 2s . co m*/ final char[] buffer = new char[4002]; IntStream.range(0, 4002).forEach((i) -> buffer[i] = String.valueOf(i % 10).charAt(0)); ReaderInputStream isr = new ReaderInputStream(new CharArrayReader(buffer), Charset.defaultCharset()); // - set the value of the input parameter to the input stream ps.setAsciiStream(2, isr, 4002); ps.execute(); isr.close(); final ResultSet resultSet = stmt.executeQuery("select * from clobtest"); final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); JdbcCommon.convertToAvroStream(resultSet, outStream, false); final byte[] serializedBytes = outStream.toByteArray(); assertNotNull(serializedBytes); // Deserialize bytes to records final InputStream instream = new ByteArrayInputStream(serializedBytes); final DatumReader<GenericRecord> datumReader = new GenericDatumReader<>(); try (final DataFileStream<GenericRecord> dataFileReader = new DataFileStream<>(instream, datumReader)) { GenericRecord record = null; while (dataFileReader.hasNext()) { // Reuse record object by passing it to next(). This saves us from // allocating and garbage collecting many objects for files with // many items. record = dataFileReader.next(record); Integer id = (Integer) record.get("ID"); Object o = record.get("TEXT"); if (id == 41) { assertNull(o); } else { assertNotNull(o); assertEquals(4002, o.toString().length()); } } } } }
From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java
protected CharArrayReader getArrayReader(Reader reader, long size) throws IOException { char[] buf = new char[8192]; CharArrayWriter bufWriter = new CharArrayWriter((size > 0) ? (int) size : 8192); BufferedReader bufReader = new BufferedReader(reader, 8192); for (int read = bufReader.read(buf); read > 0; read = bufReader.read(buf)) { bufWriter.write(buf, 0, read);/*from w w w . j a v a 2 s . c om*/ } bufWriter.flush(); return new CharArrayReader(bufWriter.toCharArray()); }
From source file:org.apache.click.servlet.MockRequest.java
/** * This feature is not implemented at this time as we are not supporting * binary servlet input. This functionality may be added in the future. * * @return The reader/*from w w w. ja v a2 s . co m*/ * @throws IOException If an I/O related problem occurs */ public BufferedReader getReader() throws IOException { return new BufferedReader(new CharArrayReader(new char[0])); }