/** * Reads all of the lines from a {@link Readable} object. The lines do not include * line-termination characters, but do include other leading and trailing whitespace. * * <p>Does not close the {@code Readable}. If reading files or resources you should use the {@link * Files#readLines} and {@link Resources#readLines} methods. * * @param r the object to read from * @return a mutable {@link List} containing all the lines * @throws IOException if an I/O error occurs */ public static List<String> readLines(Readable r) throws IOException { List<String> result = new ArrayList<String>(); LineReader lineReader = new LineReader(r); String line; while ((line = lineReader.readLine()) != null) { result.add(line); } return result; }
/** * Streams lines from a {@link Readable} object, stopping when the processor returns {@code false} * or all lines have been read and returning the result produced by the processor. Does not close * {@code readable}. Note that this method may not fully consume the contents of {@code readable} * if the processor stops processing early. * * @throws IOException if an I/O error occurs * @since 14.0 */ public static <T> T readLines(Readable readable, LineProcessor<T> processor) throws IOException { checkNotNull(readable); checkNotNull(processor); LineReader lineReader = new LineReader(readable); String line; while ((line = lineReader.readLine()) != null) { if (!processor.processLine(line)) { break; } } return processor.getResult(); }
public static int readTextLines( java.io.InputStream strm, LineReader consumer, int bufsiz, String cmnt, int mode, Object cbdata) throws java.io.IOException { java.io.InputStreamReader cstrm = new java.io.InputStreamReader(strm); java.io.BufferedReader bstrm = new java.io.BufferedReader(cstrm, bufsiz); int lno = 0; String line; try { while ((line = bstrm.readLine()) != null) { try { if (cmnt != null) { int pos = line.indexOf(cmnt); if (pos != -1) line = line.substring(0, pos); line = line.trim(); if (line.length() == 0) continue; } if (consumer.processLine(line, ++lno, mode, cbdata)) break; } catch (Exception ex) { throw new java.io.IOException( "LineReader callback failed on line=" + lno + ": " + line + " - " + ex, ex); } } } finally { bstrm.close(); } return lno; }
/* * Position the input stream at the start of the first record. */ private void positionAtFirstRecord(FSDataInputStream stream) throws IOException { if (start > 0) { // Advance to the start of the first line in our slice. // We use a temporary LineReader to read a partial line and find the // start of the first one on or after our starting position. // In case our slice starts right at the beginning of a line, we need to back // up by one position and then discard the first line. start -= 1; stream.seek(start); LineReader reader = new LineReader(stream); int bytesRead = reader.readLine(buffer, (int) Math.min(MAX_LINE_LENGTH, end - start)); start = start + bytesRead; stream.seek(start); } // else // if start == 0 we're starting at the beginning of a line pos = start; }
private void load0(Properties properties, LineReader lr) throws IOException { char[] convtBuf = new char[1024]; int limit; int keyLen; int valueStart; char c; boolean hasSep; boolean precedingBackslash; while ((limit = lr.readLine()) >= 0) { c = 0; keyLen = 0; valueStart = limit; hasSep = false; precedingBackslash = false; while (keyLen < limit) { c = lr.lineBuf[keyLen]; // need check if escaped. if ((c == '=' || c == ':') && !precedingBackslash) { valueStart = keyLen + 1; hasSep = true; break; } else if ((c == ' ' || c == '\t' || c == '\f') && !precedingBackslash) { valueStart = keyLen + 1; break; } if (c == '\\') { precedingBackslash = !precedingBackslash; } else { precedingBackslash = false; } keyLen++; } while (valueStart < limit) { c = lr.lineBuf[valueStart]; if (c != ' ' && c != '\t' && c != '\f') { if (!hasSep && (c == '=' || c == ':')) { hasSep = true; } else { break; } } valueStart++; } String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf); String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf); properties.put(key, value); } }
/** Reads a line from a file, returning null on EOF. */ @Override public StringValue readLine(long length) throws IOException { try { StringValue line = _lineReader.readLine(_env, this, length); return line; } catch (IOException e) { _isTimeout = true; _isEOF = true; log.log(Level.FINER, e.toString(), e); return _env.getEmptyString(); } }
public void start(String[] args) throws Exception { if (lineReader == null) { lineReader = new DefaultLineReader(); } running = true; while (running) { print("hazelcast[" + namespace + "] > "); try { final String command = lineReader.readLine(); handleCommand(command); } catch (Throwable e) { e.printStackTrace(); } } }
/* * Read a single record. * * Reads a single line of input and scans it with scanQseqLine, which * sets key and value accordingly. The method updates this.pos. * * @return The number of bytes read. If no bytes were read, the EOF was reached. */ private int lowLevelQseqRead(Text key, SequencedFragment value) throws IOException { int bytesRead = lineReader.readLine(buffer, MAX_LINE_LENGTH); pos += bytesRead; if (bytesRead >= MAX_LINE_LENGTH) { String line; try { line = Text.decode(buffer.getBytes(), 0, 500); } catch (java.nio.charset.CharacterCodingException e) { line = "(line not convertible to printable format)"; } throw new RuntimeException( "found abnormally large line (length " + bytesRead + ") at " + makePositionMessage(pos - bytesRead) + ": " + line); } else if (bytesRead > 0) scanQseqLine(buffer, key, value); return bytesRead; }
private static void runConsole(QueryRunner queryRunner, ClientSession session) { try (TableNameCompleter tableNameCompleter = new TableNameCompleter(queryRunner); LineReader reader = new LineReader(getHistory(), tableNameCompleter)) { tableNameCompleter.populateCache(); StringBuilder buffer = new StringBuilder(); while (true) { // read a line of input from user String prompt = PROMPT_NAME + ":" + session.getSchema(); if (buffer.length() > 0) { prompt = Strings.repeat(" ", prompt.length() - 1) + "-"; } String line = reader.readLine(prompt + "> "); // add buffer to history and clear on user interrupt if (reader.interrupted()) { String partial = squeezeStatement(buffer.toString()); if (!partial.isEmpty()) { reader.getHistory().add(partial); } buffer = new StringBuilder(); continue; } // exit on EOF if (line == null) { System.out.println(); return; } // check for special commands if this is the first line if (buffer.length() == 0) { String command = line.trim(); if (command.endsWith(";")) { command = command.substring(0, command.length() - 1).trim(); } switch (command.toLowerCase(ENGLISH)) { case "exit": case "quit": return; case "help": System.out.println(); System.out.println(getHelpText()); continue; } } // not a command, add line to buffer buffer.append(line).append("\n"); // execute any complete statements String sql = buffer.toString(); StatementSplitter splitter = new StatementSplitter(sql, ImmutableSet.of(";", "\\G")); for (Statement split : splitter.getCompleteStatements()) { Optional<Object> statement = getParsedStatement(split.statement()); if (statement.isPresent() && isSessionParameterChange(statement.get())) { session = processSessionParameterChange(statement.get(), session); queryRunner.setSession(session); tableNameCompleter.populateCache(); } else { OutputFormat outputFormat = OutputFormat.ALIGNED; if (split.terminator().equals("\\G")) { outputFormat = OutputFormat.VERTICAL; } process(queryRunner, split.statement(), outputFormat, true); } reader.getHistory().add(squeezeStatement(split.statement()) + split.terminator()); } // replace buffer with trailing partial statement buffer = new StringBuilder(); String partial = splitter.getPartialStatement(); if (!partial.isEmpty()) { buffer.append(partial).append('\n'); } } } catch (IOException e) { System.err.println("Readline error: " + e.getMessage()); } }
@Override public String readLine() throws IOException { return mDelegate.readLine(); }
@Override public void close() throws IOException { mDelegate.close(); }
@Override public boolean load() { groups = new HashMap<String, Group>(); groupsint = new HashMap<Integer, Group>(); accesslevels = new HashMap<String, AccessLevel>(); accesslevelsint = new HashMap<Integer, AccessLevel>(); List<String> lines = FileHandler.getLines("groups"); Group group; LineReader r; int id; String name, commands, worlds; for (int i = 0; i < lines.size(); i++) { r = new LineReader(lines.get(i)); id = r.nextInt(); name = r.nextStr(); commands = r.nextStr(); worlds = r.nextStr(); group = new Group(id, name, commands, worlds); groups.put(group.getName(), group); groupsint.put(group.getId(), group); } FFLog.newInit("Accessgroups", groups.size()); List<String> lines2 = FileHandler.getLines("accesslevels"); AccessLevel access; String usernameformat, accessgroups; Boolean admingroup, canbuild; for (int i = 0; i < lines2.size(); i++) { r = new LineReader(lines2.get(i)); id = r.nextInt(); name = r.nextStr(); usernameformat = r.nextStr(); accessgroups = r.nextStr(); admingroup = r.nextBool(); canbuild = r.nextBool(); access = new AccessLevel(id, getGroups(accessgroups), name, usernameformat, canbuild, admingroup); accesslevels.put(access.getName(), access); accesslevelsint.put(access.getId(), access); } FFLog.newInit("Accesslevels", accesslevels.size()); return true; }
/** * Parses those lines in the configuration files that content the fields of the SetupDataType. * * @param configBuffer configuration file contents * @param format format of the configuration file * @throws IOException if can't read the file */ public void readConfiguration(LineReader configBuffer, int format) throws IOException { boolean bool; origin = new Point(configBuffer.readInteger(), configBuffer.readInteger()); grid_size = configBuffer.readInteger(); frozen = configBuffer.readBoolean(); raster = configBuffer.readBoolean(); subNetNo = configBuffer.readInteger(); flags = configBuffer.readInteger(); layers = configBuffer.readInteger(); updateType = configBuffer.readInteger(); bool = configBuffer.readBoolean(); top_label_type = configBuffer.readInteger(); if (!bool || top_label_type < 0 || top_label_type > WINNER) top_label_type = NOTHING; bool = configBuffer.readBoolean(); base_label_type = configBuffer.readInteger(); if (!bool || base_label_type < 0 || base_label_type > WINNER) base_label_type = NOTHING; show_links = configBuffer.readBoolean(); show_directions = configBuffer.readBoolean(); show_weights = configBuffer.readBoolean(); double pos = 0, neg = 0; pos = configBuffer.readDouble(); neg = configBuffer.readDouble(); if (pos < -neg) link_trigger = pos; else link_trigger = -neg; unit_max = 1 / configBuffer.readDouble(); if (format >= 3) { link_max = configBuffer.readDouble(); siteName = configBuffer.readText(); color_index = String.valueOf(configBuffer.readInteger()); while (color_index.length() < 6) color_index = "0" + color_index; try { text_color = index2color(color_index.substring(0, 2)); background_color = index2color(color_index.substring(2, 4)); selection_color = index2color(color_index.substring(4, 6)); } catch (Exception ex) { throw (new IOException("Error in configuration file.")); } } }
public static HttpResponse readHttpResponse(LineReader input) throws IOException { final int code; final String reasonPhrase; // First line. { byte[] firstLine = input.readUpTo0x0D0A(); if (firstLine.length < 7 - 2) { throw new IOException("Malformed response"); } int space1Pos = byteIndexOf((byte) ' ', firstLine, 0); if (space1Pos == -1) { throw new IOException("Malformed response"); } int space2Pos = byteIndexOf((byte) ' ', firstLine, space1Pos + 1); if (space2Pos == -1) { throw new IOException("Malformed response"); } if (space2Pos - space1Pos != 4) { throw new IOException("Malformed response"); } int codeTemp = 0; for (int i = space1Pos + 1; i < space2Pos; i++) { codeTemp = codeTemp * 10 + firstLine[i] - (byte) '0'; } code = codeTemp; int reasonPhraseStart = space2Pos + 1; reasonPhrase = new String(firstLine, reasonPhraseStart, firstLine.length - space2Pos - 1, ASCII_CHARSET); } // Fields. final Map<String, String> responseFields; { responseFields = new HashMap<String, String>(); while (true) { byte[] line = input.readUpTo0x0D0A(); if (line.length == 0) { break; } String lineStr = new String(line, UTF_8_CHARSET); int colonPos = lineStr.indexOf(':'); if (colonPos == -1) { throw new IOException("Malformed response field"); } if (colonPos == 0) { throw new IOException("Malformed response field: empty key"); } String key = lineStr.substring(0, colonPos).toLowerCase(); if (lineStr.length() > colonPos + 1 && lineStr.charAt(colonPos + 1) == ' ') { colonPos++; } String value = lineStr.substring(colonPos + 1); Object conflict = responseFields.put(key, value); if (conflict != null) { throw new IOException("Malformed response field: duplicated field: " + key); } } } return new HttpResponse() { @Override public int getCode() { return code; } @Override public String getReasonPhrase() { return reasonPhrase; } @Override public Map<String, String> getFields() { return responseFields; } }; }
/** * Finds the start position in the property file. We assume that the key is the first match on a * line. * * @param propertyName the property name * @return the start position of the property name in the file, -1 if not found */ private int findPropertyNameStartPosition(String propertyName) { // Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19319 InputStream stream = null; LineReader lineReader = null; String encoding; try { encoding = fPropertiesFile.getCharset(); } catch (CoreException e1) { encoding = "ISO-8859-1"; // $NON-NLS-1$ } try { stream = createInputStream(fPropertiesFile); lineReader = new LineReader(stream, encoding); } catch (CoreException cex) { // failed to get input stream JavaPlugin.log(cex); return -1; } catch (IOException e) { if (stream != null) { try { stream.close(); } catch (IOException ce) { JavaPlugin.log(ce); } } return -1; } int start = 0; try { StringBuffer buf = new StringBuffer(80); int eols = lineReader.readLine(buf); int keyLength = propertyName.length(); while (eols > 0) { String line = buf.toString(); int i = line.indexOf(propertyName); int charPos = i + keyLength; char terminatorChar = 0; boolean hasNoValue = (charPos >= line.length()); if (i > -1 && !hasNoValue) terminatorChar = line.charAt(charPos); if (line.trim().startsWith(propertyName) && (hasNoValue || Character.isWhitespace(terminatorChar) || terminatorChar == '=')) { start += line.indexOf(propertyName); eols = -17; // found key } else { start += line.length() + eols; buf.setLength(0); eols = lineReader.readLine(buf); } } if (eols != -17) start = -1; // key not found in file. See bug 63794. This can happen if the key contains escaped // characters. } catch (IOException ex) { JavaPlugin.log(ex); return -1; } finally { try { lineReader.close(); } catch (IOException ex) { JavaPlugin.log(ex); } } return start; }