@Deprecated public void save() { String stats = collect(); String filename = AppConfig.outputDir + "/" + map.getSimpleFileName() + ".csv"; // if file exists, remove it (new File(filename)).delete(); CharSink sink = Files.asCharSink(new File(filename), Charsets.UTF_8); try { sink.write(stats); } catch (IOException e) { e.printStackTrace(); } logger.info("Exported statistics to: {}", filename); }
@Override public void writeQueries(final CorpusQuerySet2016 queries, final CharSink sink) throws IOException { final StringBuilder sb = new StringBuilder(); int numEntryPoints = 0; for (final CorpusQuery2016 query : QUERY_ORDERING.sortedCopy(queries)) { for (final CorpusQueryEntryPoint entryPoint : ENTRY_POINT_ORDERING .sortedCopy(query.entryPoints())) { sb.append(entryPointString(query, entryPoint)).append("\n"); ++numEntryPoints; } } log.info("Writing {} queries with {} entry points to {}", queries.queries().size(), numEntryPoints, sink); sink.write(sb.toString()); }
@Override public void writeCorpusEventFrames(final CorpusEventLinking corpusEventLinking, final CharSink sink) throws IOException { checkArgument(noneEqualForHashable(FluentIterable.from(corpusEventLinking.corpusEventFrames()) .transform(id()))); try (Writer writer = sink.openBufferedStream()) { for (final CorpusEventFrame corpusEventFrame : BY_ID .sortedCopy(corpusEventLinking.corpusEventFrames())) { final List<DocEventFrameReference> sortedDocEventFrames = DocEventFrameReference.canonicalOrdering() .sortedCopy(corpusEventFrame.docEventFrames()); writer.write( corpusEventFrame.id() + "\t" + FluentIterable.from(sortedDocEventFrames) .transform(canonicalStringFunction()) .join(SPACE_JOINER) + "\n"); } } }
public void testGet_io() throws IOException { assertEquals(-1, ArbitraryInstances.get(InputStream.class).read()); assertEquals(-1, ArbitraryInstances.get(ByteArrayInputStream.class).read()); assertEquals(-1, ArbitraryInstances.get(Readable.class).read(CharBuffer.allocate(1))); assertEquals(-1, ArbitraryInstances.get(Reader.class).read()); assertEquals(-1, ArbitraryInstances.get(StringReader.class).read()); assertEquals(0, ArbitraryInstances.get(Buffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(CharBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(ByteBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(ShortBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(IntBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(LongBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(FloatBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(DoubleBuffer.class).capacity()); ArbitraryInstances.get(PrintStream.class).println("test"); ArbitraryInstances.get(PrintWriter.class).println("test"); assertNotNull(ArbitraryInstances.get(File.class)); assertFreshInstanceReturned( ByteArrayOutputStream.class, OutputStream.class, Writer.class, StringWriter.class, PrintStream.class, PrintWriter.class); assertEquals(ByteSource.empty(), ArbitraryInstances.get(ByteSource.class)); assertEquals(CharSource.empty(), ArbitraryInstances.get(CharSource.class)); assertNotNull(ArbitraryInstances.get(ByteSink.class)); assertNotNull(ArbitraryInstances.get(CharSink.class)); }
/** * * @param path * @param p * @param needEncrypts * 암호화 할 키 값 조건 */ public static void storeProperties(String path, Properties p, Comparable<String> needEncrypts) { final EncryptedProperties ep = encryptedProperties(p); Iterable<String> lines = Iterables.transform(ep.stringPropertyNames(), k -> { String v = ep.getProperty(k); if (0 == needEncrypts.compareTo(k)) v = Secures.encrypts(v); return k + "=" + v; }); CharSink sink = Files.asCharSink(Paths.get(path).toFile(), Charsets.UTF_8); try { sink.writeLines(lines); } catch (Exception e) { log.error("fail to store properties cause: {}", e.getMessage()); log.debug("detail cause", e); } }
@Override public void finish() throws IOException { final CharSink textSink = Files.asCharSink(new File(outputDir, outputName + FILE_SUFFIX), Charsets.UTF_8); final ByteSink jsonSink = Files.asByteSink(new File(outputDir, outputName + FILE_SUFFIX + ".json")); final SummaryConfusionMatrix summaryConfusionMatrix = summaryConfusionMatrixB.build(); // Output the summaries and add a final newline final FMeasureCounts fMeasure = SummaryConfusionMatrices.FMeasureVsAllOthers(summaryConfusionMatrix, PRESENT); textSink.write(StringUtils.NewlineJoiner.join( SummaryConfusionMatrices.prettyPrint(summaryConfusionMatrix), fMeasure.compactPrettyString(), "")); // Empty string creates a bare newline at the end JacksonSerializer.builder().forJson().prettyOutput().build().serializeTo(fMeasure, jsonSink); // Call finish on the observers for (final ScoringEventObserver observer : scoringEventObservers) { observer.finish(outputDir); } }
@Test public void testOverridenLoad() throws IOException, InvalidConfigurationException { C config = newTestConfig(); File tempFile = File.createTempFile("config", ".txt"); URL modifiedURL = Resources.getResource(getClass(), getModifiedResource()); CharSource in = Resources.asByteSource(modifiedURL).asCharSource(Charsets.UTF_8); CharSink out = Files.asCharSink(tempFile, Charsets.UTF_8); in.copyTo(out); load(config, tempFile, AnnotationConfig.class.getResource(getDefaultResource())); assertEquals(112, config.getExample1()); assertArrayEquals(new String[] {"This is", "stupid test"}, config.getExample2().toArray(new String[config.getExample2().size()])); assertEquals("Yr Mum", config.getExample4()); assertEquals("Is ugly", config.getExample5()); // Overridden but still default assertEquals("I'm happy today", config.getExample6()); // Still has default config value, not specified in default config assertEquals(Food.TACO, config.getFood()); assertEquals(TimeUnit.HOURS.toSeconds(30), config.getTime()); }
@Test public void testLoadSaveEquals() throws IOException, InvalidConfigurationException { C config = newTestConfig(); File tempFile = File.createTempFile("config", ".yml"); URL modifiedURL = Resources.getResource(getClass(), getModifiedResource()); URL defaultURL = Resources.getResource(getClass(), getDefaultResource()); CharSource originalIn = Resources.asByteSource(modifiedURL).asCharSource(Charsets.UTF_8); CharSink out = Files.asCharSink(tempFile, Charsets.UTF_8); CharSource fileIn = Files.asCharSource(tempFile, Charsets.UTF_8); originalIn.copyTo(out); load(config, tempFile, defaultURL); save(config, tempFile, defaultURL); List<String> originalLines = originalIn.readLines(); originalLines = Lists.transform(originalLines, (s) -> s.replaceAll("\\s", "")); // Strip whitespace List<String> fileLines = fileIn.readLines(); fileLines = Lists.transform(fileLines, (s) -> s.replaceAll("\\s", "")); // Strip whitespace assertEquals(originalLines, fileLines); }
public void writeSeedScript(final File scriptPath) { final CharSource script = Resources.asCharSource(getClass().getResource("seedScript"), Charsets.UTF_8); final CharSink charSink = Files.asCharSink(scriptPath, Charsets.UTF_8); try { final StringBuilder scriptBuilder = new StringBuilder(); scriptBuilder.append(script.read()); for(final User user : users) { final StringBuilder line = new StringBuilder(); line.append("add_user('"); line.append(user.username); line.append("', '"); line.append(user.password); line.append("', '"); line.append(user.apiKey); line.append("')\n"); scriptBuilder.append(line); logger.debug("Adding user: " + line); } charSink.write(scriptBuilder); } catch(final IOException ioException) { throw new RuntimeException(ioException); } }
private void writeLinesFrom(Iterable<String> services) throws IOException { new CharSink() { @Override public Writer openStream() throws IOException { return getFiler() .createResource(StandardLocation.CLASS_OUTPUT, key.packageName, key.relativeName) .openWriter(); } }.writeLines(services, "\n"); }
public void saveTo(final CorpusQueryAssessments store, final CharSink sink) throws IOException { final Writer out = sink.openStream(); for (final QueryResponse2016 q : by2016Ordering().immutableSortedCopy(store.queryReponses())) { final Optional<String> metadata = Optional.fromNullable(store.metadata().get(q)); if (metadata.isPresent()) { out.write("#" + metadata.get() + "\n"); } final QueryAssessment2016 assessment = Optional.fromNullable(store.assessments().get(q)).or(QueryAssessment2016.UNASSESSED); final ImmutableList.Builder<String> pjStrings = ImmutableList.builder(); for (final CharOffsetSpan pj : Ordering.natural() .immutableSortedCopy(q.predicateJustifications())) { pjStrings.add(dashJoiner.join(pj.startInclusive(), pj.endInclusive())); } final String pjString = commaJoiner.join(pjStrings.build()); final String systemIDs = StringUtils.commaJoiner() .join(FluentIterable.from(store.queryResponsesToSystemIDs().get(q)) .transform(SymbolUtils.desymbolizeFunction()).toSet()); final String line = tabJoiner.join(q.queryID(), q.docID(), systemIDs, pjString, assessment.name()); out.write(line + "\n"); } out.close(); }
@Override public void write(ResponseLinking responseLinking, CharSink sink) throws IOException { final List<String> lines = Lists.newArrayList(); for (final ResponseSet responseSet : responseLinking.responseSets()) { lines.add(renderLine(responseSet, responseLinking)); } // incompletes last lines.add("INCOMPLETE\t" + Joiner.on("\t").join( transform(responseLinking.incompleteResponses(), ResponseFunctions.uniqueIdentifier()))); sink.writeLines(lines, "\n"); }
private static void logCoverage(String leftName, Set<Symbol> leftDocIds, String rightName, Set<Symbol> rightDocIds, CharSink out) throws IOException { final String msg = String.format( "%d documents in %s; %d in %s. %d in common, %d left-only, %d right-only", leftDocIds.size(), leftName, rightDocIds.size(), rightName, Sets.intersection(leftDocIds, rightDocIds).size(), Sets.difference(leftDocIds, rightDocIds).size(), Sets.difference(rightDocIds, leftDocIds).size()); log.info(msg); out.write(msg); }
/** * Format the given input (a Java compilation unit) into the output stream. * * @throws FormatterException if the input cannot be parsed */ public void formatSource(CharSource input, CharSink output) throws FormatterException, IOException { // TODO(cushon): proper support for streaming input/output. Input may // not be feasible (parsing) but output should be easier. output.write(formatSource(input.read())); }
@Override public Writer openWriter() throws IOException { final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE); return new Writer() { @Override public void write(char[] chars, int start, int end) throws IOException { stringBuilder.append(chars, start, end - start); } @Override public void flush() throws IOException {} @Override public void close() throws IOException { try { formatter.formatSource( CharSource.wrap(stringBuilder), new CharSink() { @Override public Writer openStream() throws IOException { return fileObject.openWriter(); } }); } catch (FormatterException e) { // An exception will happen when the code being formatted has an error. It's better to // log the exception and emit unformatted code so the developer can view the code which // caused a problem. try (Writer writer = fileObject.openWriter()) { writer.append(stringBuilder.toString()); } if (messager != null) { messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName()); } } } }; }
void dumpDotGraph( IdentityHashMap<PlanGraphNode<?>, List<PlanGraphNode<?>>> adj, CharSink sink) { try (Writer out = sink.openBufferedStream()) { out.write("digraph planGraph {\n"); Set<PlanGraphNode<?>> visited = Sets.newIdentityHashSet(); Iterable<PlanGraphNode<?>> effectiveRoots = effectiveRoots(); for (PlanGraphNode<?> root : effectiveRoots) { out.write(" root -> " + dotName(root) + " [color=blue];\n"); } writeForwardGraph(effectiveRoots, visited, out); for (Map.Entry<PlanGraphNode<?>, List<PlanGraphNode<?>>> e : adj.entrySet()) { PlanGraphNode<?> n = e.getKey(); List<PlanGraphNode<?>> preceders = e.getValue(); String name = dotName(n); if (preceders.isEmpty()) { if (!visited.contains(n)) { out.write(" " + name + ";\n"); } } else { for (PlanGraphNode<?> p : preceders) { out.write(" " + dotName(p) + " -> " + name + " [color=red];\n"); } } } out.write("}\n"); } catch (IOException ex) { context.log.error("Failed to write dot graph", ex); } }
public static void writeFile(String fileName, String message){ try { CharSink charSink = Files.asCharSink(new File(fileName), Charsets.UTF_8, FileWriteMode.APPEND); charSink.write(message + "\n"); }catch(Exception e){ } }
@Test public void testJoinFileWriter() throws Exception{ File tempFile = new File("testTempFile.txt"); tempFile.deleteOnExit(); CharSink charSink = Files.asCharSink(tempFile, Charsets.UTF_8); Writer writer = charSink.openStream(); String[] values = new String[]{"foo", "bar","baz"}; Joiner.on("|").appendTo(writer,values); writer.flush(); writer.close(); String fromFileString = Files.toString(tempFile, Charsets.UTF_8); assertThat(fromFileString, is("foo|bar|baz")); }
@Test public void copyToCharSinkTest() throws Exception { File source = new File("src/main/resources/sampleTextFileTwo.txt"); File dest = new File("src/test/resources/sampleCopy.txt"); dest.deleteOnExit(); charSource = Files.asCharSource(source,Charsets.UTF_8); CharSink charSink = Files.asCharSink(dest,Charsets.UTF_8); charSource.copyTo(charSink); assertThat(Files.toString(dest,Charsets.UTF_8),is(Files.toString(source,Charsets.UTF_8))); }
@Test public void givenUsingGuava_whenWritingReaderContentsToFile_thenCorrect() throws IOException { Reader initialReader = new StringReader("Some text"); File targetFile = new File("src/test/resources/targetFile.txt"); com.google.common.io.Files.touch(targetFile); CharSink charSink = com.google.common.io.Files.asCharSink(targetFile, Charset.defaultCharset(), FileWriteMode.APPEND); charSink.writeFrom(initialReader); initialReader.close(); }
@Test public void whenWriteUsingCharSink_thenWritten() throws IOException { final String expectedValue = "Hello world"; final File file = new File("src/test/resources/test.out"); final CharSink sink = Files.asCharSink(file, Charsets.UTF_8); sink.write(expectedValue); final String result = Files.toString(file, Charsets.UTF_8); assertEquals(expectedValue, result); }
@Test public void whenWriteMultipleLinesUsingCharSink_thenWritten() throws IOException { final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom"); final File file = new File("src/test/resources/test.out"); final CharSink sink = Files.asCharSink(file, Charsets.UTF_8); sink.writeLines(names, " "); final String result = Files.toString(file, Charsets.UTF_8); final String expectedValue = Joiner.on(" ").join(names); assertEquals(expectedValue, result.trim()); }
/** * Writes out the specified {@link EDLMention}s. If a {@link #defaultKbId} was not specified, * an exception will be thrown if any EDL mentions have an absent KB ID. */ public void writeEDLMentions(Iterable<EDLMention> edlMentions, CharSink sink) throws IOException { final List<String> lines = Lists.newArrayList(); for (final EDLMention edlMention : edlMentions) { lines.add(toLine(edlMention)); } sink.writeLines(lines, "\n"); }
private static void trueMain(final String[] args) throws IOException { final Parameters input = Parameters.loadSerifStyle(new File(args[0])); final String resolved = input.dump(); final CharSink output = Files.asCharSink(new File(args[1]), Charsets.UTF_8, FileWriteMode.APPEND); output.write(resolved); }
/** * Writes map entries from symbols to file absolute paths to a file. Each line has a mapping with * the key and value separated by a single tab. The file will have a trailing newline. Note that * the same "key" may appear in the file with multiple mappings. */ public static void writeSymbolToFileEntries(final Iterable<Map.Entry<Symbol, File>> entries, final CharSink sink) throws IOException { writeUnixLines( transform( MapUtils.transformValues(entries, toAbsolutePathFunction()), TO_TAB_SEPARATED_ENTRY), sink); }
public static void writeSymbolMultimap(Multimap<Symbol, Symbol> mm, CharSink charSink) throws IOException { final Joiner tabJoiner = Joiner.on('\t'); writeUnixLines(transform(mm.asMap().entrySet(), new Function<Map.Entry<Symbol, Collection<Symbol>>, String>() { @Override public String apply(Map.Entry<Symbol, Collection<Symbol>> input) { return input.getKey() + "\t" + tabJoiner.join(input.getValue()); } }), charSink); }
private void process(Context context, String templateName, String targetPath) throws IOException { URL templateUrl = Resources.getResource(IpmiCommandNameTest.class, templateName); CharSource source = Resources.asCharSource(templateUrl, StandardCharsets.UTF_8); File file = new File(targetPath); CharSink sink = Files.asCharSink(file, StandardCharsets.UTF_8); try (Reader r = source.openBufferedStream()) { try (Writer w = sink.openBufferedStream()) { engine.evaluate(context, w, file.getName(), r); } } }
void writeQueries(CorpusQuerySet2016 queries, CharSink sink) throws IOException;
void writeCorpusEventFrames(CorpusEventLinking corpusEventFrames, CharSink sink) throws IOException;
public void logDocIdsWithUndeterminedGenre(CharSink sink) throws IOException { sink.write(Joiner.on("\n").join(docIdsWithUndeterminedGenre.build())); }
private PsiFile doCreate( PsiDirectory dir, String className, String fqnExtended ) throws IncorrectOperationException { Project project = dir.getProject(); String fileName = className + ".java"; VirtualFile srcRoot = ProjectRootManager.getInstance( project ).getFileIndex().getSourceRootForFile( dir.getVirtualFile() ); dir = getPsiDirectoryForExtensionClass( dir, fqnExtended, srcRoot ); final PsiPackage pkg = JavaDirectoryService.getInstance().getPackage( dir ); if( pkg == null ) { throw new IncorrectOperationException( ManBundle.message( "error.new.artifact.nopackage" ) ); } String text = "package " + pkg.getQualifiedName() + ";\n" + "\n" + "import manifold.ext.api.Extension;\n" + "import manifold.ext.api.This;\n" + "import " + fqnExtended + ";\n" + "\n" + "@Extension\n" + "public class " + className + " {\n" + " public static " + processTypeVars( dir, fqnExtended, StubBuilder::makeTypeVar ) + "void helloWorld(@This " + ClassUtil.extractClassName( fqnExtended ) + processTypeVars( dir, fqnExtended, PsiNamedElement::getName ) + " thiz) {\n" + " System.out.println(\"hello world!\");\n" + " }\n" + "}"; dir.checkCreateFile( fileName ); final PsiFile file = dir.createFile( fileName ); try { new CharSink() { public Writer openStream() throws IOException { return new OutputStreamWriter( file.getVirtualFile().getOutputStream( null ) ); } }.write( text ); } catch( IOException e ) { throw new IncorrectOperationException( e.getMessage(), (Throwable)e ); } return file; }
public static void writeLines(String fileName,List<String> list,Charset charset) throws IOException { CharSink cs = Files.asCharSink(new File(fileName), charset); list = PojoUtil.avoidEmptyList(list); cs.writeLines(list); }
public static void writeLines(File file,List<String> list,Charset charset) throws IOException { CharSink cs = Files.asCharSink(file, charset); list = PojoUtil.avoidEmptyList(list); cs.writeLines(list); }