private Reader markableReader(Reader r, long l) throws SQLException { if (r.markSupported() && l < 0) { boolean marked = true; try { r.mark(1000000); } catch (IOException e) { marked = false; } if (marked) return r; } StringBuffer sb = new StringBuffer(); int dim = l >= 0 ? (int) l : 4096; char[] cb = new char[dim]; int rd; try { while ((rd = r.read(cb)) >= 0) { sb.append(Arrays.copyOf(cb, rd)); if (l >= 0) break; } StringReader sr = new StringReader(sb.toString()); sr.mark(1000000); return sr; } catch (IOException e) { throw new SQLException(e); } }
/** * A static convience method for decoding an object from a String. * * <p>All exceptions are logged using LogMgr internally and then rethrown as GlueException with * the same message as written to the log. * * @param title The name to be given to the object when decoded. * @param text The Glue format text to be decoded. * @throws GlueException If unable to decode the string. */ public static Object decodeString(String title, String text) throws GlueException { try { GlueDecoderImpl gd = new GlueDecoderImpl(); StringReader in = null; try { in = new StringReader(text); GlueParser parser = new GlueParser(in); return parser.Decode(gd, gd.getState()); } catch (ParseException ex) { throw new GlueException(ex); } catch (TokenMgrError ex) { throw new GlueException(ex); } finally { in.close(); } } catch (GlueException ex) { String msg = ("Unable to Glue decode: " + title + "\n" + " " + ex.getMessage()); LogMgr.getInstance().log(LogMgr.Kind.Glu, LogMgr.Level.Severe, msg); throw new GlueException(msg); } catch (Exception ex) { String msg = Exceptions.getFullMessage("INTERNAL ERROR:", ex, true, true); LogMgr.getInstance().log(LogMgr.Kind.Glu, LogMgr.Level.Severe, msg); throw new GlueException(msg); } }
public static List<String> analyze(String content) { List<String> resultList = null; try { // 创建分词对象 resultList = new ArrayList<String>(1); resultList.add(content); IKAnalyzer analyer = new IKAnalyzer(true); analyer.setUseSmart(true); StringReader reader = new StringReader(content); // 分词 TokenStream tokenStream = analyer.tokenStream("", reader); CharTermAttribute term = tokenStream.getAttribute(CharTermAttribute.class); // 遍历分词数据 while (tokenStream.incrementToken()) { if (!term.toString().isEmpty()) { resultList.add(term.toString()); } } reader.close(); } catch (IOException ex) { logger.error("分词出错", ex); } return resultList; }
public void parseBlockComments(String text) { blockComments = new Vector(); StringReader buffer = new StringReader(text); int ch; boolean blkComment = false; int cnt = 0; int[] offsets = new int[2]; boolean done = false; try { while (!done) { switch (ch = buffer.read()) { case -1: { if (blkComment) { offsets[1] = cnt; blockComments.addElement(offsets); } done = true; break; } case '/': { ch = buffer.read(); if ((ch == '*') && (!blkComment)) { offsets = new int[2]; offsets[0] = cnt; blkComment = true; cnt++; } else { cnt++; } cnt++; break; } case '*': { if (blkComment) { ch = buffer.read(); cnt++; if (ch == '/') { blkComment = false; offsets[1] = cnt; blockComments.addElement(offsets); } } cnt++; break; } default: { cnt++; break; } } } } catch (IOException e) { // ignore errors } }
public String getRemains() throws IOException { StringBuilder remains = new StringBuilder(); for (int c = sr.read(); c != -1; c = sr.read()) { remains.append((char) c); } return remains.toString(); }
public List<String> getAVDList() { if (buffer == null || buffer.length() < 1) return null; StringReader reader = new StringReader(buffer.toString()); BufferedReader read = new BufferedReader(reader); String line = null; ArrayList<String> list = new ArrayList<String>(); try { while ((line = read.readLine()) != null) { int idx = line.indexOf(PREFIX_NAME); if (idx > -1) { list.add(line.substring(idx + PREFIX_NAME.length()).trim()); } } } catch (IOException e) { AndroidCore.log(IStatus.ERROR, "Error parsing the AVD list", e); return null; } finally { try { read.close(); reader.close(); } catch (IOException e) { /*ignored*/ } } return list; }
public Document getTestDocument(String s) throws Exception { StringReader reader = new StringReader(s); InputSource inputSource = new InputSource(reader); Document doc = parser.parse(inputSource); reader.close(); return doc; }
public byte[] decode(String code) { ByteArrayOutputStream baos = new ByteArrayOutputStream((code.length() * 3 / 4)); StringReader sr; if (code.endsWith(Character.toString(padding))) { sr = new StringReader(code.substring(0, code.indexOf(padding))); } else { sr = new StringReader(code); } char[] c = new char[4]; int[] b = new int[4]; int len; try { int count = 0; while ((len = sr.read(c, 0, 4)) == 4) { b[0] = decode[c[0]]; b[1] = decode[c[1]]; b[2] = decode[c[2]]; b[3] = decode[c[3]]; baos.write(((b[0] & 0x3f) << 2) | ((b[1] & 0x30) >> 4)); baos.write(((b[1] & 0x0f) << 4) | ((b[2] & 0x3c) >> 2)); baos.write(((b[2] & 0x03) << 6) | (b[3] & 0x3f)); count++; if (count == 19) { sr.mark(1); count = 0; if (sr.read() != 10) { sr.reset(); } } } b[0] = decode[c[0]]; b[1] = decode[c[1]]; b[2] = decode[c[2]]; b[3] = decode[c[3]]; if (len == 2) { baos.write(((b[0] & 0x3f) << 2) | ((b[1] & 0x30) >> 4)); } else if (len == 3) { baos.write(((b[0] & 0x3f) << 2) | ((b[1] & 0x30) >> 4)); baos.write(((b[1] & 0x0f) << 4) | ((b[2] & 0x3c) >> 2)); } return baos.toByteArray(); } catch (java.io.IOException e) { return null; } catch (RuntimeException e) { return null; } }
public boolean compare(String baselinecontent, String testresult) throws Exception { StringReader baserdr = new StringReader(baselinecontent); StringReader resultrdr = new StringReader(testresult); // Diff the two files Diff diff = new Diff("Testing " + getTitle()); boolean pass = !diff.doDiff(baserdr, resultrdr); baserdr.close(); resultrdr.close(); return pass; }
public static void main(String argv[]) throws Exception { StringReader in = new StringReader("aaaaaaaaaaaaaaa"); try { in.mark(-1); } catch (IllegalArgumentException e) { return; } throw new Exception(" Negative marklimit value should throw an exception"); }
@Override public int read(char[] b, int off, int len) throws IOException { if (stringReader == null) return -1; // Reader already closed int ret = 0; for (ret = stringReader.read(b, off, len); ret == -1; ret = stringReader.read(b, off, len)) { if (!advanceToNextRow()) return -1; // Behind last row } return ret; }
private Ruleset unmarshallRuleset(String documentAsString) { // unmarshall doc StringReader stringReader = new StringReader(documentAsString); try { return (Ruleset) sbb.getUnmarshaller().unmarshal(stringReader); } catch (Exception e) { logger.error("unmarshalling of ruleset failed", e); return null; } finally { stringReader.close(); } }
private static int getNextNonWhitespace(StringReader reader) { try { int nextChar = reader.read(); while (nextChar >= 0 && Character.isWhitespace((char) nextChar)) { nextChar = reader.read(); } return nextChar; } catch (IOException exception) { // This cannot happen because we're reading from a StringReader. return -1; } }
public static Properties stringToProperties(String str) { ParamChecker.notNull(str, "str"); try { StringReader sr = new StringReader(str); Properties props = new Properties(); props.load(sr); sr.close(); return props; } catch (IOException ex) { throw new RuntimeException(ex); } }
/** * Compile a string into a function or SimpleVariable. * * <p>Called by {@link #compileString(String)} when that has detected "${". * * <p>Calls {@link CompoundVariable#getNamedFunction(String)} if it detects: '(' - start of * parameter list '}' - end of function call * * @param reader points to input after the "${" * @return the function or variable object (or a String) */ Object makeFunction(StringReader reader) throws InvalidVariableException { char[] current = new char[1]; char previous = ' '; // TODO - why use space? StringBuilder buffer = new StringBuilder(); Object function; try { while (reader.read(current) == 1) { if (current[0] == '\\') { if (reader.read(current) == 0) { break; } previous = ' '; buffer.append(current[0]); continue; } else if (current[0] == '(' && previous != ' ') { String funcName = buffer.toString(); function = CompoundVariable.getNamedFunction(funcName); if (function instanceof Function) { ((Function) function).setParameters(parseParams(reader)); if (reader.read(current) == 0 || current[0] != '}') { reader.reset(); // set to start of string char[] cb = new char[100]; reader.read(cb); // return deliberately ignored throw new InvalidVariableException( "Expected } after " + funcName + " function call in " + new String(cb)); } if (function instanceof TestListener) { StandardJMeterEngine.register((TestListener) function); } return function; } else { // Function does not exist, so treat as per missing variable buffer.append(current[0]); } continue; } else if (current[0] == '}') { // variable, or function with no parameter list function = CompoundVariable.getNamedFunction(buffer.toString()); if (function instanceof Function) { // ensure that setParameters() is called. ((Function) function).setParameters(new LinkedList<CompoundVariable>()); } buffer.setLength(0); return function; } else { buffer.append(current[0]); previous = current[0]; } } } catch (IOException e) { log.error("Error parsing function: " + buffer.toString(), e); return null; } log.warn("Probably an invalid function string: " + buffer.toString()); return buffer.toString(); }
static Properties info(BulkReply reply) { Properties info = new Properties(); // use the same charset as the library StringReader stringReader = new StringReader(new String(reply.data(), Charsets.UTF_8)); try { info.load(stringReader); } catch (Exception ex) { throw new RedisSystemException("Cannot read Redis info", ex); } finally { stringReader.close(); } return info; }
public String stemToken(String token) { char[] w = new char[501]; String stemmed = new String(); stemmed = ""; Stemmer s = new Stemmer(); // try // { StringReader in = new StringReader(token); try { while (true) { int ch = in.read(); if (Character.isLetter((char) ch)) { int j = 0; while (true) { ch = Character.toLowerCase((char) ch); w[j] = (char) ch; if (j < 500) j++; ch = in.read(); if (!Character.isLetter((char) ch)) { /* to test add(char ch) */ for (int c = 0; c < j; c++) s.add(w[c]); /* or, to test add(char[] w, int j) */ /* s.add(w, j); */ s.stem(); { String u; /* and now, to test toString() : */ u = s.toString(); stemmed = stemmed + " " + u; /* to test getResultBuffer(), getResultLength() : */ /* u = new String(s.getResultBuffer(), 0, s.getResultLength()); */ // System.out.print(u); } break; } } } if (ch < 0) break; // System.out.print((char)ch); } } catch (IOException e) { System.out.println("error reading "); } // } // catch (FileNotFoundException e) { System.out.println("file not found"); } return stemmed; }
private void dummy(String xmlstring) { try { xmlstring = xmlstring.trim(); log.info("xmlstring:\r\n" + xmlstring); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader reader = new StringReader(xmlstring); InputSource inputSource = new InputSource(reader); Document doc = db.parse(inputSource); // CharArrayReader characterStream = new CharArrayReader(xmlstring.toCharArray()); // InputSource is = new InputSource(characterStream); // Document doc = db.parse(is); // doc.getDocumentElement().normalize(); log.info("Root element " + doc.getDocumentElement().getNodeName()); NodeList nodeLst = doc.getElementsByTagName("PersoneFisiche"); log.info("cycling..."); for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); if (fstNode.getNodeType() == Node.ELEMENT_NODE) { Element fstElmnt = (Element) fstNode; NodeList idElmntLst = fstElmnt.getElementsByTagName("Id"); Element idElmnt = (Element) idElmntLst.item(0); NodeList idList = idElmnt.getChildNodes(); log.info("Id : " + ((Node) idList.item(0)).getNodeValue()); NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("Nome"); Element fstNmElmnt = (Element) fstNmElmntLst.item(0); NodeList fstNm = fstNmElmnt.getChildNodes(); log.info("First Name : " + ((Node) fstNm.item(0)).getNodeValue()); NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("Cognome"); Element lstNmElmnt = (Element) lstNmElmntLst.item(0); NodeList lstNm = lstNmElmnt.getChildNodes(); log.info("Last Name : " + ((Node) lstNm.item(0)).getNodeValue()); } } reader.close(); } catch (IOException e) { log.severe("Eccezione IO: " + e.getMessage()); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
public Properties convert(String source) { if (source == null) { return null; } Properties info = new Properties(); StringReader stringReader = new StringReader(source); try { info.load(stringReader); } catch (Exception ex) { throw new RedisSystemException("Cannot read Redis info", ex); } finally { stringReader.close(); } return info; }
public void transform(OntModel inputModel, OntModel outputModel, NIFParameters nifParameters) { this.prefix = nifParameters.getPrefix(); String uri = this.prefix + "char=0,"; // only supporting RFC5147 string atm contextResource = outputModel.createIndividual( uri, outputModel.createClass(NIFOntClasses.RFC5147String.getUri())); contextResource.addOntClass(NIFOntClasses.Context.getOntClass(outputModel)); contextResource.addOntClass(NIFOntClasses.String.getOntClass(outputModel)); contextResource.addProperty( NIFDatatypeProperties.beginIndex.getDatatypeProperty(outputModel), "0"); if (!nifParameters.getOptions().has("informat")) { log.warn("informat parameter empty, please choose informat=file or informat=text"); } if (!nifParameters.getOptions().has("tagset")) { log.warn( "No tagset chosen, please choose an OLiA tagset from: https://github.com/NLP2RDF/software/blob/master/java-maven/vocabularymodule/OLiA/src/main/java/org/nlp2rdf/vm/olia/models"); } else { loadTagset(nifParameters.getOptions().valueOf("tagset").toString()); } if (nifParameters.getOptions().valueOf("intype").equals("file")) { if (nifParameters.getOptions().valueOf("informat").equals("text")) { File input = new File(nifParameters.getOptions().valueOf("i").toString()); FileReader reader = null; try { reader = new FileReader(input); this.transformConLL(reader, inputModel, outputModel, nifParameters); reader.close(); } catch (FileNotFoundException fnf) { log.error("Could not open file " + nifParameters.getOptions().valueOf("i").toString()); } catch (IOException e) { log.error("Could not read file " + nifParameters.getOptions().valueOf("i").toString()); } } } else if (nifParameters.getOptions().valueOf("intype").equals("url")) { log.error("URL input not yet supported"); } else { if (nifParameters.getOptions().valueOf("informat").equals("text")) { StringReader reader = new StringReader(nifParameters.getOptions().valueOf("i").toString()); this.transformConLL(reader, inputModel, outputModel, nifParameters); reader.close(); } } }
/** * Reads up to <code>len</code> chars of data from another String into an array of chars. An * attempt is made to read as many as <code>len</code> chars, but a smaller number may be read, * possibly zero. The number of chars actually read is returned as an integer. <br> * <br> * This method blocks until input data is available, end of file is detected, or an exception is * thrown. <br> * <br> * If <code>b</code> is <code>null</code>, a <code>NullPointerException</code> is thrown. <br> * <br> * If <code>off</code> is negative, or <code>len</code> is negative, or <code>off+len</code> is * greater than the length of the array <code>b</code>, then an <code>IndexOutOfBoundsException * </code> is thrown. <br> * <br> * If <code>len</code> is zero, then no chars are read and 0 is returned; otherwise, there is an * attempt to read at least one char. If no char is available because the stream is at end of * file, the value -1 is returned; otherwise, at least one char is read and stored into <code>b * </code>. <br> * <br> * The first char read is stored into element <code>b[off]</code>, the next one into <code> * b[off+1]</code>, and so on. The number of chars read is, at most, equal to <code>len</code>. * Let <i>k</i> be the number of chars actually read; these chars will be stored in elements * <code>b[off]</code> through <code>b[off+k-1]</code>, leaving elements <code>b[off+k]</code> * through <code>b[off+len-1]</code> unaffected. <br> * <br> * In every case, elements <code>b[0]</code> through <code>b[off-1]</code> and elements <code> * b[off+len]</code> through <code>b[b.length-1]</code> are unaffected. <br> * <br> * If the first char cannot be read for any reason other than end of file, then an <code> * IOException</code> is thrown. In particular, an <code>IOException</code> is thrown if the input * stream has been closed. * * @param b A buffer into which the converted input is stored. * @param off The offset in the buffer at which to begin writing. * @param len The amount of chars to be received and written into the buffer. * @return The total number of chars read into the buffer, or -1 if there is no more data because * the end of the stream has been reached. */ public int read(char[] b, int off, int len) throws IOException { char[] hex = new char[2 * len]; int charsRead = in.read(hex); if (charsRead == -1) return -1; if (charsRead % 2 == 1) throw new IOException("HexStringInputStream: Unexpected end of file"); for (int i = 0; i < charsRead; i += 2) { int d1 = digits.indexOf((char) hex[i]); if (d1 == -1) throw new IOException( "HexStringInputStream: Invalid input character: '" + ((char) hex[i]) + "' (" + ((int) hex[i]) + ")"); int d2 = digits.indexOf((char) hex[i + 1]); if (d2 == -1) throw new IOException( "HexStringInputStream: Invalid input character: '" + ((char) hex[i + 1]) + "' (" + ((int) hex[i + 1]) + ")"); b[i / 2] = (char) ((d2 << 4) | d1); } return charsRead / 2; }
private void execute() { try { Method mth = PreparedStatement.class.getDeclaredMethod(this.methodName, this.argClasses); mth.invoke(wrapped, args); if (args[1] instanceof StringReader) { StringReader sr = (StringReader) args[1]; sr.reset(); } if (args[1] instanceof InputStream && ("setAsciiStream".equals(methodName) || "setUnicodeStream".equals(methodName))) { ((InputStream) args[1]).reset(); } } catch (Exception e) { throw new RuntimeException(e); } }
/** * Marks the current position in this input stream. A subsequent call to the <code>reset</code> * method repositions this stream at the last marked position so that subsequent reads re-read the * same chars. * * <p>The <code>readlimit</code> argument tells this input stream to allow that many chars to be * read before the mark position gets invalidated. * * <p>The general contract of mark is that, if the method <code>markSupported</code> returns * <code>true</code>, the stream somehow remembers all the chars read after the call to mark and * stands ready to supply those same chars again if and whenever the method <code>reset</code> is * called. However, the stream is not required to remember any data at all if more than <code> * readlimit</code> chars are read from the stream before <code>reset</code> is called. * * @param readlimit The maximum limit of chars that can be read before the mark position becomes * invalid. */ public void mark(int readlimit) { try { in.mark(readlimit * 2); } catch (Exception e) { System.err.println(e); } }
protected static NodeList xpathGetNodesMatching(final String xml, final String expression) throws XPathExpressionException { final XPath query = XPathFactory.newInstance().newXPath(); StringReader sr = null; InputSource is = null; NodeList nodes = null; try { sr = new StringReader(xml); is = new InputSource(sr); nodes = (NodeList) query.evaluate(expression, is, XPathConstants.NODESET); } finally { sr.close(); IOUtils.closeQuietly(sr); } return nodes; }
/** * Compile a general string into a list of elements for a CompoundVariable. * * <p>Calls {@link #makeFunction(StringReader)} if it detects an unescaped "${". * * <p>Removes escapes from '$', ',' and '\'. * * @param value string containing the function / variable references (if any) * @return list of Strings or Objects representing functions */ LinkedList<Object> compileString(String value) throws InvalidVariableException { StringReader reader = new StringReader(value); LinkedList<Object> result = new LinkedList<Object>(); StringBuilder buffer = new StringBuilder(); char previous = ' '; // TODO - why use space? char[] current = new char[1]; try { while (reader.read(current) == 1) { if (current[0] == '\\') { // Handle escapes previous = current[0]; if (reader.read(current) == 0) { break; } // Keep the '\' unless it is one of the escapable chars '$' ',' or '\' // N.B. This method is used to parse function parameters, so must treat ',' as special if (current[0] != '$' && current[0] != ',' && current[0] != '\\') { buffer.append(previous); // i.e. '\\' } previous = ' '; buffer.append(current[0]); continue; } else if (current[0] == '{' && previous == '$') { // found "${" buffer.deleteCharAt(buffer.length() - 1); if (buffer.length() > 0) { // save leading text result.add(buffer.toString()); buffer.setLength(0); } result.add(makeFunction(reader)); previous = ' '; } else { buffer.append(current[0]); previous = current[0]; } } if (buffer.length() > 0) { result.add(buffer.toString()); } } catch (IOException e) { log.error("Error parsing function: " + value, e); result.clear(); result.add(value); } if (result.size() == 0) { result.add(""); } return result; }
@Override public int read(char[] cbuf, int off, int len) throws IOException { if (!isBuilt) { build(); isBuilt = true; } return sourceReader.read(cbuf, off, len); }
/** * Reads the next char of data from the input stream. The value is returned as an <code>int</code> * in the range 0 to 255. If no char is available because the end of the stream has been reached, * the value -1 is returned. This method blocks until input data is available, the end of the * stream is detected, or an exception is thrown. * * @return The next char of data, or -1 if the end of the stream is reached. */ public int read() throws IOException { int d1 = in.read(); if (d1 == -1) return -1; int d2 = in.read(); if (d2 == -1) throw new IOException("HexStringInputStream: Unexpected end of file"); int i1 = digits.indexOf((char) d1); if (i1 == -1) throw new IOException( "HexStringInputStream: Invalid input character: '" + ((char) d1) + "' (" + d1 + ")"); int i2 = digits.indexOf((char) d2); if (i2 == -1) throw new IOException( "HexStringInputStream: Invalid input character: '" + ((char) d2) + "' (" + d2 + ")"); return (i2 << 4) | i1; }
/** * Same as parseFile but for a string * * @param stream * @return */ public static Document parse(String stream) { System.out.println("Parsing XML ... " + stream); StringReader reader = new StringReader(stream); InputSource inputSource = new InputSource(reader); SAXBuilder saxBuilder = new SAXBuilder(); Document doc = null; try { doc = saxBuilder.build(inputSource); } catch (IOException e) { System.out.println("Could not read source file: " + e.getMessage()); } catch (JDOMException e) { System.err.println("cannot build doc"); e.printStackTrace(); } reader.close(); return doc; }
public void testDispatcher() throws Exception { ProcessingContext processingContext; StringReader reader; StringWriter writer; String message; message = createMessage(); reader = new StringReader(message); writer = new StringWriter(); processingContext = new ProcessingContext( new WebRequestContextImpl(reader), new WebResponseContextImpl(writer)); assertEquals(Dispatcher.OK, dispatcher.dispatch(processingContext)); reader.close(); writer.close(); assertEquals(message, writer.toString()); }
public String getParameter() throws IOException { String result; if (!parameter) { return null; } parameter = false; int c = sr.read(); while (c != -1) { if (c == ')') { result = buf.toString(); buf = new StringBuilder(); return result; } buf.append((char) c); c = sr.read(); } return null; }