List of usage examples for com.google.common.io CharStreams readLines
public static List<String> readLines(Readable r) throws IOException
From source file:com.tngtech.archunit.library.plantuml.PlantUmlParser.java
private List<String> readLines(URL url) { try (InputStreamReader in = new InputStreamReader(url.openStream(), UTF_8)) { return CharStreams.readLines(in); } catch (IOException e) { throw new PlantUmlParseException("Could not parse diagram from " + url, e); }//from w w w. ja v a 2 s . c om }
From source file:edu.umd.cloud9.collection.clue.ClueWarcDocnoMappingBuilder.java
/** * Runs this tool.// w ww. ja v a 2s .c o m */ public int run(String[] args) throws IOException { DocnoMapping.DefaultBuilderOptions options = DocnoMapping.BuilderUtils.parseDefaultOptions(args); if (options == null) { return -1; } LOG.info("Tool name: " + ClueWarcDocnoMappingBuilder.class.getSimpleName()); LOG.info(" - input path: " + options.collection); LOG.info(" - output file: " + options.docnoMapping); FileSystem fs = FileSystem.get(getConf()); FSDataOutputStream out = fs.create(new Path(options.docnoMapping), true); final InputStream in = ClueWarcDocnoMapping.class.getResourceAsStream("docno.mapping"); List<String> lines = CharStreams.readLines(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return in; } }, Charsets.UTF_8)); out.write((Joiner.on("\n").join(lines) + "\n").getBytes()); out.close(); return 0; }
From source file:com.cloudera.oryx.rdf.serving.web.TrainServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { RDFGenerationManager generationManager = getGenerationManager(); Generation generation = generationManager.getCurrentGeneration(); if (generation == null) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "API method unavailable until model has been built and loaded"); return;//from w w w .ja v a 2 s . co m } InboundSettings inboundSettings = getInboundSettings(); TreeBasedClassifier forest = generation.getForest(); Map<Integer, BiMap<String, Integer>> columnToCategoryNameToIDMapping = generation .getColumnToCategoryNameToIDMapping(); int totalColumns = getTotalColumns(); for (CharSequence line : CharStreams.readLines(request.getReader())) { generationManager.append(line); String[] tokens = DelimitedDataUtils.decode(line); if (tokens.length != totalColumns) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong column count"); return; } Feature target = null; Feature[] features = new Feature[totalColumns]; // Too big by 1 but makes math easier try { for (int col = 0; col < features.length; col++) { if (col == inboundSettings.getTargetColumn()) { target = buildFeature(col, tokens[col], columnToCategoryNameToIDMapping); features[col] = IgnoredFeature.INSTANCE; } else { features[col] = buildFeature(col, tokens[col], columnToCategoryNameToIDMapping); } } } catch (IllegalArgumentException iae) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad input line"); return; } Preconditions.checkNotNull(target); Example example = new Example(target, features); forest.update(example); } }
From source file:io.soabase.web.context.TextLoader.java
private Map<String, Map<String, String>> loadTextFromZip() { Map<String, Map<String, String>> text = Maps.newHashMap(); try {/*w ww. ja v a2s .c om*/ ZipFile zipFile = new ZipFile(assetsFile); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File entryFile = new File(entry.getName()); if (!entry.isDirectory() && textDir.equals(entryFile.getParent())) { try (InputStream stream = zipFile.getInputStream(entry)) { text.put(getKey(entryFile.getName()), read(entryFile.getName(), CharStreams.readLines(new InputStreamReader(stream)).stream())); } } } } catch (IOException e) { throw new RuntimeException(e); } return text; }
From source file:org.obm.push.mail.transformer.TextToHtml.java
@Override public InputStream transform(InputStream input, Charset charset) throws IOException { Preconditions.checkNotNull(input);// ww w . j ava2 s . c om Preconditions.checkNotNull(charset); List<String> lines = CharStreams.readLines(new InputStreamReader(input, charset)); String html = "<html><body>" + Joiner.on("<br/>").join(lines) + "</body></html>"; return new ByteArrayInputStream(html.getBytes(charset)); }
From source file:name.marcelomorales.siqisiqi.pdfbox.CoordinatesGenerator.java
public void generarPdf(OutputStream os, String template, Map<String, Object> m, String path, String coordenates, float fontSize, float ancho) throws IOException { long t = System.currentTimeMillis(); PDDocument doc = null;//from w w w .jav a 2 s . c o m try { doc = PDDocument.load(new File(path)); List pages = doc.getDocumentCatalog().getAllPages(); PDPage sourcePage = (PDPage) pages.get(0); boolean append = sourcePage.getContents() != null; PDPageContentStream contentStream = new PDPageContentStream(doc, sourcePage, append, true); StringReader fileReader = null; try { fileReader = new StringReader(template); List<String> list = CharStreams.readLines(fileReader); boolean textHasBegun = false; float currentOffset = 0f; for (String line : list) { if (line == null) { continue; } if (line.startsWith("#")) { continue; } final Iterable<String> str = Splitter.on(',').omitEmptyStrings().trimResults().split(line); final String[] split = Iterables.toArray(str, String.class); if (split == null || split.length < 4) { continue; } if (Character.isDigit(split[0].charAt(0))) { if (textHasBegun) { contentStream.endText(); } contentStream.beginText(); textHasBegun = true; contentStream.moveTextPositionByAmount(parseFloat(split[0]), parseFloat(split[1])); } else { contentStream.moveTextPositionByAmount(currentOffset, 0); } if (!textHasBegun) { LOGGER.warn("Hay un posible mal uso de un .ree", new Throwable()); contentStream.beginText(); textHasBegun = true; } PDType1Font font; if ("b".equals(split[2])) { font = HELVETICA_BOLD; } else { font = HELVETICA; } contentStream.setFont(font, fontSize); Object text = null; if (split[3].startsWith("\"")) { // TODO: text = substring(split[3], 1, -1); } else { // TODO: text = new PropertyModel(m, split[3]).getObject(); } if (text == null) { LOGGER.warn("Propiedad {} no se encuentra", split[3]); //contentStream.drawString("ERROR: propiedad no encontrada"); contentStream.drawString(" "); } else { String string = text.toString(); currentOffset = font.getStringWidth(string) * ancho; contentStream.drawString(string); } } if (textHasBegun) { contentStream.endText(); } } finally { Closeables.closeQuietly(fileReader); } contentStream.close(); try { doc.save(os); } catch (COSVisitorException e) { throw new IOException("Ha ocurrido un error al escribir en el Os", e); } } finally { if (doc != null) { doc.close(); } LOGGER.info("Me ha tomado {} milisegundos hacer el pdf", System.currentTimeMillis() - t); } }
From source file:net.kebernet.skillz.util.OutputUtterances.java
private static Stream<String> formatUtterances(InvokableMethod invokableMethod) { return Optional.ofNullable(invokableMethod.getNativeMethod().getAnnotation(Utterances.class)) .map(utterances -> Arrays.stream(utterances.value()).flatMap(s -> { if (!s.startsWith(INCLUDE_URL)) { return Stream.of(s); } else { try { URL url = new URL(s.substring(INCLUDE_URL.length())); return CharStreams.readLines(new InputStreamReader(url.openStream())).stream() .map(String::trim).filter(l -> !l.isEmpty()); } catch (java.io.IOException e) { LOGGER.log(Level.WARNING, "Failed to fetch included url " + s.substring(INCLUDE_URL.length() + 1)); return Stream.empty(); }// w w w. j a va2s . c om } }).map(s -> new StringBuilder(invokableMethod.getName()).append(" ").append(s).toString())) .orElse(Stream.empty()); }
From source file:eu.numberfour.n4js.JSLibSingleTestConfigProvider.java
/** * @param resourceName/* w ww. jav a 2 s.c om*/ * the classpath-relative location of the to-be-read resource */ private static List<String> getFileLines(final String resourceName) throws IOException { InputSupplier<InputStreamReader> readerSupplier = CharStreams .newReaderSupplier(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName); } }, Charsets.UTF_8); return CharStreams.readLines(readerSupplier); }
From source file:de.dentrassi.pm.database.schema.Parser.java
public UpgradeTask loadTask(final String name) throws Exception { final URL entry = this.bundle.getEntry(name); try (final Reader r = new InputStreamReader(entry.openStream(), StandardCharsets.UTF_8)) { final List<String> lines = CharStreams.readLines(r); final StringBuilder sb = new StringBuilder(); for (final String line : lines) { if (line.startsWith("--#")) { processMetaCommand(line); } else if (isActive()) { sb.append(line).append('\n'); }/*from w ww .ja v a 2 s . c o m*/ } final String sql = sb.toString(); final String[] sqlToks = sql.split(";"); final List<String> sqls = new LinkedList<>(); for (final String sqlTok : sqlToks) { final String s = sqlTok.trim(); if (!s.isEmpty()) { sqls.add(s); } } if (sqls.isEmpty()) { return null; } return new StatementTask(sqls); } }
From source file:org.caleydo.data.importer.tcga.model.ClinicalMapping.java
private static Collection<ClinicalMapping> readAll(String fileName, ListMultimap<String, CategoryProperty<String>> properties) { try (InputStreamReader r = new InputStreamReader( ClinicalMapping.class.getResourceAsStream("/resources/" + fileName))) { List<String> lines = CharStreams.readLines(r); lines.remove(0);//from ww w . j a v a2 s.co m Collection<ClinicalMapping> result = new ArrayList<>(); for (String line : lines) { String[] ls = line.split("\t"); ClinicalMapping mapping = new ClinicalMapping(ls[0], ls[1], EDataClass.valueOf(ls[2].toUpperCase()), EDataType.valueOf(ls[3]), Arrays.copyOfRange(ls, 4, ls.length), properties.get(ls[0])); result.add(mapping); } return result; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return Collections.emptyList(); } }