Here are the examples of the java api class java.io.Writer taken from open source projects.
1. ByResourceTypeServlet#doGet()
View license@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { Resource resource = request.getResource(); Writer w = response.getWriter(); w.write("<!DOCTYPE html PUBLIC \"-//IETF//DTD HTML 2.0//EN\">"); w.write("<html>"); w.write("<head>"); w.write("<title>Hello World Servlet</title>"); w.write("</head>"); w.write("<body>"); w.write("<h1>Hello "); w.write(resource.getPath()); w.write("</h1>"); w.write("</body>"); w.write("</html>"); log.info("Hello World Servlet"); }
2. MsvcProjectWriter#writeProject()
View license/** * Writes a project definition file. * * @param fileName * File name base, writer may append appropriate extension * @param task * cc task for which to write project * @param projectDef * project element * @param files * source files * @param targets * compilation targets * @param linkTarget * link target * @throws IOException * if error writing project file */ @Override public void writeProject(final File fileName, final CCTask task, final ProjectDef projectDef, final List<File> files, final Map<String, TargetInfo> targets, final TargetInfo linkTarget) throws IOException { // // some characters are apparently not allowed in VS project names // but have not been able to find them documented // limiting characters to alphas, numerics and hyphens String projectName = projectDef.getName(); if (projectName != null) { projectName = toProjectName(projectName); } else { projectName = toProjectName(fileName.getName()); } final String basePath = fileName.getAbsoluteFile().getParent(); final File dspFile = new File(fileName + ".dsp"); if (!projectDef.getOverwrite() && dspFile.exists()) { throw new BuildException("Not allowed to overwrite project file " + dspFile.toString()); } final File dswFile = new File(fileName + ".dsw"); if (!projectDef.getOverwrite() && dswFile.exists()) { throw new BuildException("Not allowed to overwrite project file " + dswFile.toString()); } final CommandLineCompilerConfiguration compilerConfig = getBaseCompilerConfiguration(targets); if (compilerConfig == null) { throw new BuildException("Unable to generate Visual Studio project " + "when Microsoft C++ is not used."); } Writer writer = new BufferedWriter(new FileWriter(dspFile)); writer.write("# Microsoft Developer Studio Project File - Name=\""); writer.write(projectName); writer.write("\" - Package Owner=<4>\r\n"); writer.write("# Microsoft Developer Studio Generated Build File, Format Version "); writer.write(this.version); writer.write("\r\n"); writer.write("# ** DO NOT EDIT **\r\n\r\n"); writeComments(writer, projectDef.getComments()); final String outputType = task.getOuttype(); final String subsystem = task.getSubsystem(); String targtype = "Win32 (x86) Dynamic-Link Library"; String targid = "0x0102"; if ("executable".equals(outputType)) { if ("console".equals(subsystem)) { targtype = "Win32 (x86) Console Application"; targid = "0x0103"; } else { targtype = "Win32 (x86) Application"; targid = "0x0101"; } } else if ("static".equals(outputType)) { targtype = "Win32 (x86) Static Library"; targid = "0x0104"; } writer.write("# TARGTYPE \""); writer.write(targtype); writer.write("\" "); writer.write(targid); writer.write("\r\n\r\nCFG="); writer.write(projectName + " - Win32 Debug"); writer.write("\r\n"); writeMessage(writer, projectName, targtype); writer.write("# Begin Project\r\n"); if (this.version.equals("6.00")) { writer.write("# PROP AllowPerConfigDependencies 0\r\n"); } writer.write("# PROP Scc_ProjName \"\"\r\n"); writer.write("# PROP Scc_LocalPath \"\"\r\n"); writer.write("CPP=cl.exe\r\n"); writer.write("MTL=midl.exe\r\n"); writer.write("RSC=rc.exe\r\n"); writer.write("\r\n!IF \"$(CFG)\" == \"" + projectName + " - Win32 Release\"\r\n"); writeConfig(writer, false, projectDef.getDependencies(), basePath, compilerConfig, linkTarget, targets); writer.write("\r\n!ELSEIF \"$(CFG)\" == \"" + projectName + " - Win32 Debug\"\r\n"); writeConfig(writer, true, projectDef.getDependencies(), basePath, compilerConfig, linkTarget, targets); writer.write("\r\n!ENDIF\r\n"); writer.write("# Begin Target\r\n\r\n"); writer.write("# Name \"" + projectName + " - Win32 Release\"\r\n"); writer.write("# Name \"" + projectName + " - Win32 Debug\"\r\n"); final File[] sortedSources = getSources(files); if (this.version.equals("6.00")) { final String sourceFilter = "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"; final String headerFilter = "h;hpp;hxx;hm;inl"; final String resourceFilter = "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"; writer.write("# Begin Group \"Source Files\"\r\n\r\n"); writer.write("# PROP Default_Filter \"" + sourceFilter + "\"\r\n"); for (final File sortedSource1 : sortedSources) { if (!isGroupMember(headerFilter, sortedSource1) && !isGroupMember(resourceFilter, sortedSource1)) { writeSource(writer, basePath, sortedSource1); } } writer.write("# End Group\r\n"); writer.write("# Begin Group \"Header Files\"\r\n\r\n"); writer.write("# PROP Default_Filter \"" + headerFilter + "\"\r\n"); for (final File sortedSource : sortedSources) { if (isGroupMember(headerFilter, sortedSource)) { writeSource(writer, basePath, sortedSource); } } writer.write("# End Group\r\n"); writer.write("# Begin Group \"Resource Files\"\r\n\r\n"); writer.write("# PROP Default_Filter \"" + resourceFilter + "\"\r\n"); for (final File sortedSource : sortedSources) { if (isGroupMember(resourceFilter, sortedSource)) { writeSource(writer, basePath, sortedSource); } } writer.write("# End Group\r\n"); } else { for (final File sortedSource : sortedSources) { writeSource(writer, basePath, sortedSource); } } writer.write("# End Target\r\n"); writer.write("# End Project\r\n"); writer.close(); // // write workspace file // writer = new BufferedWriter(new FileWriter(dswFile)); writeWorkspace(writer, projectDef, projectName, dspFile); writer.close(); }
3. JsonTest#testPersonObject()
View license@Ignore @Test public void testPersonObject() throws Exception { Person p = Json.fromJson(Person.class, getFileAsInputStreamReader("org/nutz/json/person.txt")); StringBuilder sb = new StringBuilder(); Writer w = new OutputStreamWriter(new StringOutputStream(sb)); w.write(p.dump()); w.write("\n"); w.write(p.getFather().dump()); w.write("\n"); w.write(p.getCompany().getName()); w.write("\n"); w.write(p.getCompany().getCreator().dump()); w.flush(); w.close(); assertTrue(Streams.equals(new StringInputStream(sb), getClass().getResourceAsStream("/org/nutz/json/person.expect.txt"))); }
4. ByPathServlet#doGet()
View license@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { Writer w = response.getWriter(); w.write("<!DOCTYPE html PUBLIC \"-//IETF//DTD HTML 2.0//EN\">"); w.write("<html>"); w.write("<head>"); w.write("<title>Hello World Servlet</title>"); w.write("</head>"); w.write("<body>"); w.write("<h1>Hello World!</h1>"); w.write("</body>"); w.write("</html>"); log.info("Hello World Servlet"); }
5. CommitMessageWriter#writeTo()
View license/** * @see MessageBodyWriter#writeTo(Object, Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, * javax.ws.rs.core.MultivaluedMap, java.io.OutputStream) */ @Override public void writeTo(Revision revision, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { Writer writer = new OutputStreamWriter(entityStream); writer.write('['); writer.write(revision.getBranch()); writer.write(' '); writer.write(revision.getId()); writer.write(']'); writer.write(' '); writer.write(revision.getMessage()); writer.write('\n'); writer.flush(); }
6. TestWARCReader#buildRecordContent()
View license/** * build minimal WARC record byte stream. * @param recinfo WARCRecordInfo with record metadata and content * @return InputStream reading from created record bits * @throws IOException */ public static InputStream buildRecordContent(WARCRecordInfo recinfo) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); Writer w = new OutputStreamWriter(buf); w.write("WARC/1.0" + CRLF); w.write("WARC-Type: " + recinfo.getType() + CRLF); if (StringUtils.isNotEmpty(recinfo.getUrl())) { w.write("WARC-Target-URI: " + recinfo.getUrl() + CRLF); } w.write("WARC-Date: " + recinfo.getCreate14DigitDate() + CRLF); if (recinfo.getExtraHeaders() != null) { ANVLRecord headers = recinfo.getExtraHeaders(); for (Element el : headers) { w.write(el.getLabel() + ": " + el.getValue() + CRLF); } } w.write("Content-Type: " + recinfo.getMimetype() + CRLF); w.write("Content-Length: " + recinfo.getContentLength() + CRLF); w.write(CRLF); w.flush(); IOUtils.copy(recinfo.getContentStream(), buf); buf.write((CRLF + CRLF).getBytes()); buf.close(); return new ByteArrayInputStream(buf.toByteArray()); }
7. TestWARCRecordInfo#buildHttpRedirectResponseBlock()
View licensepublic static byte[] buildHttpRedirectResponseBlock(String statusline, String location) throws IOException { assert statusline.startsWith("3"); ByteArrayOutputStream blockbuf = new ByteArrayOutputStream(); Writer bw = new OutputStreamWriter(blockbuf); bw.write("HTTP/1.0 " + statusline + CRLF); bw.write("Content-Length: " + 0 + CRLF); bw.write("Content-Type: text/html" + CRLF); bw.write("Location: " + location + CRLF); bw.write(CRLF); bw.close(); return blockbuf.toByteArray(); }
8. TransparentReplayRendererTest#buildPartialContentResponseBlock()
View licenseprotected static byte[] buildPartialContentResponseBlock(String ctype, byte[] payloadBytes, long startPos, long instanceSize) throws IOException { assertTrue(startPos + payloadBytes.length <= instanceSize); final String CRLF = "\r\n"; final String contentRange = String.format("bytes %d-%d/%d", startPos, startPos + payloadBytes.length - 1, instanceSize); ByteArrayOutputStream blockbuf = new ByteArrayOutputStream(); Writer bw = new OutputStreamWriter(blockbuf); bw.write("HTTP/1.0 206 Partial Content" + CRLF); bw.write("Content-Type: " + ctype + CRLF); bw.write("Content-Range: " + contentRange + CRLF); bw.write("Content-Length: " + payloadBytes.length + CRLF); bw.write(CRLF); bw.close(); blockbuf.write(payloadBytes); return blockbuf.toByteArray(); }
9. AppendableWriterTest#testWriteMethods()
View licensepublic void testWriteMethods() throws IOException { StringBuilder builder = new StringBuilder(); Writer writer = new AppendableWriter(builder); writer.write("Hello".toCharArray()); writer.write(','); // only lower 16 bits are important writer.write(0xBEEF0020); writer.write("Wo"); writer.write("Whirled".toCharArray(), 3, 2); writer.write("Mad! Mad, I say", 2, 2); assertEquals("Hello, World!", builder.toString()); }
10. DiskLruCacheTest#createJournalWithHeader()
View licenseprivate void createJournalWithHeader(String magic, String version, String appVersion, String valueCount, String blank, String... bodyLines) throws Exception { Writer writer = new FileWriter(journalFile); writer.write(magic + "\n"); writer.write(version + "\n"); writer.write(appVersion + "\n"); writer.write(valueCount + "\n"); writer.write(blank + "\n"); for (String line : bodyLines) { writer.write(line); writer.write('\n'); } writer.close(); }
11. UnixSocketConnection#writeHttpHeaders()
View licenseprivate void writeHttpHeaders(OutputStream output, String method, String path, String query, List<Pair<String, ?>> headers) throws IOException { final Writer writer = new OutputStreamWriter(output); writer.write(method); writer.write(' '); writer.write(path); if (!Strings.isNullOrEmpty(query)) { writer.write("?"); writer.write(query); } writer.write(" HTTP/1.1\r\n"); for (Pair<String, ?> header : headers) { writer.write(header.first); writer.write(": "); writer.write(String.valueOf(header.second)); writer.write("\r\n"); } // Host header is mandatory in HTTP 1.1 writer.write("Host: \r\n\r\n"); writer.flush(); }
12. DiskLruCacheTest#createJournalWithHeader()
View licenseprivate void createJournalWithHeader(String magic, String version, String appVersion, String valueCount, String blank, String... bodyLines) throws Exception { Writer writer = new FileWriter(journalFile); writer.write(magic + "\n"); writer.write(version + "\n"); writer.write(appVersion + "\n"); writer.write(valueCount + "\n"); writer.write(blank + "\n"); for (String line : bodyLines) { writer.write(line); writer.write('\n'); } writer.close(); }
13. S3Sample#createSampleFile()
View license/** * Creates a temporary file with text data to demonstrate uploading a file * to Amazon S3 * * @return A newly created temporary file with text data. * * @throws IOException */ private static File createSampleFile() throws IOException { File file = File.createTempFile("aws-java-sdk-", ".txt"); file.deleteOnExit(); Writer writer = new OutputStreamWriter(new FileOutputStream(file)); writer.write("abcdefghijklmnopqrstuvwxyz\n"); writer.write("01234567890112345678901234\n"); writer.write("[email protected]#$%^&*()-=[]{};':',.<>/?\n"); writer.write("01234567890112345678901234\n"); writer.write("abcdefghijklmnopqrstuvwxyz\n"); writer.close(); return file; }
14. TestUserDefinedCounters#cleanAndCreateInput()
View licenseprivate void cleanAndCreateInput(FileSystem fs) throws IOException { fs.delete(INPUT_FILE, true); fs.delete(OUTPUT_DIR, true); OutputStream os = fs.create(INPUT_FILE); Writer wr = new OutputStreamWriter(os); wr.write("hello1\n"); wr.write("hello2\n"); wr.write("hello3\n"); wr.write("hello4\n"); wr.close(); }
15. PlatformLineWriterTest#testPlatformLineWriter()
View licensepublic void testPlatformLineWriter() throws IOException, ClassNotFoundException { String LS = System.getProperty("line.separator"); Binding binding = new Binding(); binding.setVariable("first", "Tom"); binding.setVariable("last", "Adams"); StringWriter stringWriter = new StringWriter(); Writer platformWriter = new PlatformLineWriter(stringWriter); GroovyShell shell = new GroovyShell(binding); platformWriter.write(shell.evaluate("\"$first\\n$last\\n\"").toString()); platformWriter.flush(); assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString()); stringWriter = new StringWriter(); platformWriter = new PlatformLineWriter(stringWriter); platformWriter.write(shell.evaluate("\"$first\\r\\n$last\\r\\n\"").toString()); platformWriter.flush(); assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString()); }
16. PlatformLineWriterTest#testPlatformLineWriter()
View licensepublic void testPlatformLineWriter() throws IOException, ClassNotFoundException { String LS = System.getProperty("line.separator"); Binding binding = new Binding(); binding.setVariable("first", "Tom"); binding.setVariable("last", "Adams"); StringWriter stringWriter = new StringWriter(); Writer platformWriter = new PlatformLineWriter(stringWriter); GroovyShell shell = new GroovyShell(binding); platformWriter.write(shell.evaluate("\"$first\\n$last\\n\"").toString()); platformWriter.flush(); assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString()); stringWriter = new StringWriter(); platformWriter = new PlatformLineWriter(stringWriter); platformWriter.write(shell.evaluate("\"$first\\r\\n$last\\r\\n\"").toString()); platformWriter.flush(); assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString()); }
17. TestWARCRecordInfo#buildHttpResponseBlock()
View license/** * return content-block bytes for HTTP response. * @param status HTTP status code and status text separated by a space. ex. {@code "200 OK"}. * @param ctype HTTP Content-Type * @param payloadBytes payload bytes * @param chunked if true, use chunked transfer-encoding * @return content-block bytes with HTTP status line, HTTP headers and payload. * @throws IOException */ public static byte[] buildHttpResponseBlock(String status, String ctype, byte[] payloadBytes, boolean chunked) throws IOException { ByteArrayOutputStream blockbuf = new ByteArrayOutputStream(); Writer bw = new OutputStreamWriter(blockbuf); bw.write("HTTP/1.0 " + status + CRLF); if (chunked) { bw.write("Transfer-Encoding: chunked" + CRLF); } else { bw.write("Content-Length: " + payloadBytes.length + CRLF); } if (ctype != null) { bw.write("Content-Type: " + ctype + CRLF); } bw.write(CRLF); bw.flush(); if (chunked) { writeChunked(blockbuf, payloadBytes); } else { blockbuf.write(payloadBytes); } bw.close(); return blockbuf.toByteArray(); }
18. OldWriterTest#test_appendCharSequenceIntInt()
View licensepublic void test_appendCharSequenceIntInt() throws IOException { String testString = "My Test String"; Writer tobj = new Support_ASimpleWriter(21); testString = "0123456789abcdefghijABCDEFGHIJ"; tobj.append(testString, 0, 5); assertEquals("Wrong stuff written!", "01234", tobj.toString()); tobj.append(testString, 10, 15); assertEquals("Wrong stuff written!", "01234abcde", tobj.toString()); tobj.append(testString, 20, 30); assertEquals("Wrong stuff written!", "01234abcdeABCDEFGHIJ", tobj.toString()); try { tobj.append(testString, 30, 31); fail("IndexOutOfBoundsException not thrown!"); } catch (IndexOutOfBoundsException e) { } // Just fill the writer to its limit! tobj.append(testString, 20, 21); try { tobj.append(testString, 29, 30); fail("IOException not thrown!"); } catch (IOException e) { } }
19. OldWriterTest#test_write$C()
View licensepublic void test_write$C() throws IOException { Writer tobj = new Support_ASimpleWriter(21); tobj.write("01234".toCharArray()); assertEquals("Wrong stuff written!", "01234", tobj.toString()); tobj.write("abcde".toCharArray()); assertEquals("Wrong stuff written!", "01234abcde", tobj.toString()); tobj.write("ABCDEFGHIJ".toCharArray()); assertEquals("Wrong stuff written!", "01234abcdeABCDEFGHIJ", tobj.toString()); // Just fill the writer to its limit! tobj.write("z".toCharArray()); try { tobj.write("LES JEUX SONT FAITS".toCharArray()); fail("IOException not thrown!"); } catch (IOException e) { } }
20. OldWriterTest#test_writeLjava_lang_String()
View licensepublic void test_writeLjava_lang_String() throws IOException { Writer tobj = new Support_ASimpleWriter(21); tobj.write("01234"); assertEquals("Wrong stuff written!", "01234", tobj.toString()); tobj.write("abcde"); assertEquals("Wrong stuff written!", "01234abcde", tobj.toString()); tobj.write("ABCDEFGHIJ"); assertEquals("Wrong stuff written!", "01234abcdeABCDEFGHIJ", tobj.toString()); // Just fill the writer to its limit! tobj.write("z"); try { tobj.write("LES JEUX SONT FAITS"); fail("IOException not thrown!"); } catch (IOException e) { } }
21. OldWriterTest#test_writeLjava_lang_StringII()
View licensepublic void test_writeLjava_lang_StringII() throws IOException { String testString; Writer tobj = new Support_ASimpleWriter(21); testString = "0123456789abcdefghijABCDEFGHIJ"; tobj.write(testString, 0, 5); assertEquals("Wrong stuff written!", "01234", tobj.toString()); tobj.write(testString, 10, 5); assertEquals("Wrong stuff written!", "01234abcde", tobj.toString()); tobj.write(testString, 20, 10); assertEquals("Wrong stuff written!", "01234abcdeABCDEFGHIJ", tobj.toString()); try { tobj.write(testString, 30, 1); fail("IndexOutOfBoundsException not thrown!"); } catch (IndexOutOfBoundsException e) { } // Just fill the writer to its limit! tobj.write(testString, 20, 1); try { tobj.write(testString, 29, 1); fail("IOException not thrown!"); } catch (IOException e) { } }
22. VCalendar10Format#encode()
View license/** * Serializes a PIMItem. * @param out Stream to which serialized data is written * @param encoding Character encoding to use for serialized data * @param pimItem The item to write to the stream * @throws IOException if a write error occurs */ public void encode(OutputStream out, String encoding, PIMItem pimItem) throws IOException { Writer w = new OutputStreamWriter(out, encoding); w.write("BEGIN:VCALENDAR\r\n"); w.write("VERSION:1.0\r\n"); if (pimItem instanceof Event) { encode(w, (Event) pimItem); } else if (pimItem instanceof ToDo) { encode(w, (ToDo) pimItem); } w.write("END:VCALENDAR\r\n"); w.flush(); }
23. XmlStreamReaderTest#getXmlStream()
View license/** * @param bomType no-bom, UTF-16BE-bom, UTF-16LE-bom, UTF-8-bom * @param xmlType xml, xml-prolog, xml-prolog-charset * @param streamEnc encoding of the stream * @param prologEnc encoding of the prolog * @return XML stream * @throws IOException If an I/O error occurs */ protected InputStream getXmlStream(final String bomType, final String xmlType, final String streamEnc, final String prologEnc) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); int[] bom = BOMs.get(bomType); if (bom == null) { bom = new int[0]; } for (final int element : bom) { baos.write(element); } final Writer writer = new OutputStreamWriter(baos, streamEnc); final String xmlDoc = getXML(bomType, xmlType, streamEnc, prologEnc); writer.write(xmlDoc); // PADDDING TO TEST THINGS WORK BEYOND PUSHBACK_SIZE writer.write("<da>\n"); for (int i = 0; i < 10000; i++) { writer.write("<do/>\n"); } writer.write("</da>\n"); writer.close(); return new ByteArrayInputStream(baos.toByteArray()); }
24. TestLogUtils#testLogFileInRuntimeInfo()
View license@Test public void testLogFileInRuntimeInfo() throws Exception { File dir = new File("target", UUID.randomUUID().toString()); Assert.assertTrue(dir.mkdirs()); final File logFile = new File(dir, "test.log"); Writer writer = new FileWriter(logFile); writer.write("hello\n"); writer.close(); File log4fConfig = new File(dir, "log4j.properties"); writer = new FileWriter(log4fConfig); writer.write(LogUtils.LOG4J_APPENDER_STREAMSETS_FILE_PROPERTY + "=" + logFile.getAbsolutePath()); writer.close(); RuntimeInfo runtimeInfo = Mockito.mock(RuntimeInfo.class); Mockito.when(runtimeInfo.getAttribute(Mockito.eq(RuntimeInfo.LOG4J_CONFIGURATION_URL_ATTR))).thenReturn(log4fConfig.toURI().toURL()); Assert.assertEquals(logFile.getAbsolutePath(), LogUtils.getLogFile(runtimeInfo)); }
25. XmlReaderTest#getXmlStream()
View license/** * * @param bomType no-bom, UTF-16BE-bom, UTF-16LE-bom, UTF-8-bom * @param xmlType xml, xml-prolog, xml-prolog-charset * @return XML stream */ protected InputStream getXmlStream(final String bomType, final String xmlType, final String streamEnc, final String prologEnc) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); int[] bom = BOMs.get(bomType); if (bom == null) { bom = new int[0]; } final MessageFormat xml = XMLs.get(xmlType); for (final int element : bom) { baos.write(element); } final Writer writer = new OutputStreamWriter(baos, streamEnc); final String info = INFO.format(new Object[] { bomType, xmlType, prologEnc }); final String xmlDoc = xml.format(new Object[] { streamEnc, prologEnc, info }); writer.write(xmlDoc); // PADDDING TO TEST THINGS WORK BEYOND PUSHBACK_SIZE writer.write("<da>\n"); for (int i = 0; i < 10000; i++) { writer.write("<do/>\n"); } writer.write("</da>\n"); writer.close(); return new ByteArrayInputStream(baos.toByteArray()); }
26. TestXmlReader#getXmlStream()
View license/** * * @param bomType no-bom, UTF-16BE-bom, UTF-16LE-bom, UTF-8-bom * @param xmlType xml, xml-prolog, xml-prolog-charset * @return XML stream */ protected InputStream getXmlStream(final String bomType, final String xmlType, final String streamEnc, final String prologEnc) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); int[] bom = BOMs.get(bomType); if (bom == null) { bom = new int[0]; } final MessageFormat xml = XMLs.get(xmlType); for (final int element : bom) { baos.write(element); } final Writer writer = new OutputStreamWriter(baos, streamEnc); final String info = INFO.format(new Object[] { bomType, xmlType, prologEnc }); final String xmlDoc = xml.format(new Object[] { streamEnc, prologEnc, info }); writer.write(xmlDoc); // PADDDING TO TEST THINGS WORK BEYOND PUSHBACK_SIZE writer.write("<da>\n"); for (int i = 0; i < 10000; i++) { writer.write("<do/>\n"); } writer.write("</da>\n"); writer.close(); return new ByteArrayInputStream(baos.toByteArray()); }
27. CustomPrivilegeTest#testInvalidCustomDefinitions()
View licensepublic void testInvalidCustomDefinitions() throws RepositoryException, FileSystemException, IOException { // setup the custom privilege file with cyclic references FileSystem fs = ((RepositoryImpl) superuser.getRepository()).getConfig().getFileSystem(); FileSystemResource resource = new FileSystemResource(fs, "/privileges/custom_privileges.xml"); if (!resource.exists()) { resource.makeParentDirs(); } StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><privileges><privilege isAbstract=\"false\" name=\"test\"><contains name=\"test2\"/></privilege></privileges>"); Writer writer = new OutputStreamWriter(resource.getOutputStream(), "utf-8"); writer.write(sb.toString()); writer.flush(); writer.close(); try { new PrivilegeRegistry(superuser.getWorkspace().getNamespaceRegistry(), fs); fail("Invalid names must be detected upon registry startup."); } catch (RepositoryException e) { } finally { fs.deleteFolder("/privileges"); } }
28. TestReportEvent#testLegacyReport()
View license@Test public void testLegacyReport() throws IOException { ReportEvent e2 = ReportEvent.createLegacyHtmlReport("test", "this is an old single string report"); Writer out = new OutputStreamWriter(System.out); System.out.println(e2.toText()); System.out.println(); e2.toText(out); out.flush(); System.out.println(); e2.toHtml(out); out.flush(); System.out.println(); e2.toJson(out); out.flush(); System.out.println(); }
29. AppendableWriterTest#testCloseFlush()
View licensepublic void testCloseFlush() throws IOException { SpyAppendable spy = new SpyAppendable(); Writer writer = new AppendableWriter(spy); writer.write("Hello"); assertFalse(spy.flushed); assertFalse(spy.closed); writer.flush(); assertTrue(spy.flushed); assertFalse(spy.closed); writer.close(); assertTrue(spy.flushed); assertTrue(spy.closed); }
30. AppendableWriterTest#testCloseIsFinal()
View licensepublic void testCloseIsFinal() throws IOException { StringBuilder builder = new StringBuilder(); Writer writer = new AppendableWriter(builder); writer.write("Hi"); writer.close(); try { writer.write(" Greg"); fail("Should have thrown IOException due to writer already closed"); } catch (IOException es) { } try { writer.flush(); fail("Should have thrown IOException due to writer already closed"); } catch (IOException es) { } // close()ing already closed writer is allowed writer.close(); }
31. ChannelsTest#testNewWriterWritableByteChannelString_InputNull()
View license/* * this test cannot be passed when buffer set to 0! */ public void testNewWriterWritableByteChannelString_InputNull() throws IOException { this.fouts = new FileOutputStream(tmpFile); WritableByteChannel wbChannel = Channels.newChannel(this.fouts); Writer testWriter = Channels.newWriter(wbChannel, Charset.forName(//$NON-NLS-1$ CODE_SET).newEncoder(), 1); //$NON-NLS-1$ String writebuf = ""; for (int val = 0; val < this.writebufSize / 2; val++) { writebuf = writebuf + ((char) (val + 64)); } // can write to buffer testWriter.write(writebuf); testWriter.flush(); testWriter.close(); }
32. TestMapReduceActionExecutor#testMapReduce()
View licensepublic void testMapReduce() throws Exception { FileSystem fs = getFileSystem(); Path inputDir = new Path(getFsTestCaseDir(), "input"); Path outputDir = new Path(getFsTestCaseDir(), "output"); Writer w = new OutputStreamWriter(fs.create(new Path(inputDir, "data.txt"))); w.write("dummy\n"); w.write("dummy\n"); w.close(); String actionXml = "<map-reduce>" + "<job-tracker>" + getJobTrackerUri() + "</job-tracker>" + "<name-node>" + getNameNodeUri() + "</name-node>" + getMapReduceConfig(inputDir.toString(), outputDir.toString()).toXmlString(false) + "</map-reduce>"; _testSubmit("map-reduce", actionXml); }
33. TestMapReduceActionExecutor#testMapReduceWithCredentials()
View licensepublic void testMapReduceWithCredentials() throws Exception { FileSystem fs = getFileSystem(); Path inputDir = new Path(getFsTestCaseDir(), "input"); Path outputDir = new Path(getFsTestCaseDir(), "output"); Writer w = new OutputStreamWriter(fs.create(new Path(inputDir, "data.txt"))); w.write("dummy\n"); w.write("dummy\n"); w.close(); String actionXml = "<map-reduce>" + "<job-tracker>" + getJobTrackerUri() + "</job-tracker>" + "<name-node>" + getNameNodeUri() + "</name-node>" + getMapReduceCredentialsConfig(inputDir.toString(), outputDir.toString()).toXmlString(false) + "</map-reduce>"; _testSubmitWithCredentials("map-reduce", actionXml); }
34. TestMapReduceActionExecutor#testStreaming()
View licensepublic void testStreaming() throws Exception { FileSystem fs = getFileSystem(); Path streamingJar = new Path(getFsTestCaseDir(), "jar/hadoop-streaming.jar"); InputStream is = new FileInputStream(ClassUtils.findContainingJar(StreamJob.class)); OutputStream os = fs.create(new Path(getAppPath(), streamingJar)); IOUtils.copyStream(is, os); Path inputDir = new Path(getFsTestCaseDir(), "input"); Path outputDir = new Path(getFsTestCaseDir(), "output"); Writer w = new OutputStreamWriter(fs.create(new Path(inputDir, "data.txt"))); w.write("dummy\n"); w.write("dummy\n"); w.close(); String actionXml = "<map-reduce>" + "<job-tracker>" + getJobTrackerUri() + "</job-tracker>" + "<name-node>" + getNameNodeUri() + "</name-node>" + " <streaming>" + " <mapper>cat</mapper>" + " <reducer>wc</reducer>" + " </streaming>" + getStreamingConfig(inputDir.toString(), outputDir.toString()).toXmlString(false) + "<file>" + streamingJar + "</file>" + "</map-reduce>"; _testSubmit("streaming", actionXml); }
35. URLOutputStreamTest#can_http_put()
View license@Test public void can_http_put() throws IOException, ExecutionException, InterruptedException { final BlockingQueue<String> data = new LinkedBlockingDeque<String>(); Rest r = new Rest(webbit); r.PUT("/.cucumber/stepdefs.json", new HttpHandler() { @Override public void handleHttpRequest(HttpRequest req, HttpResponse res, HttpControl ctl) throws Exception { data.offer(req.body()); res.end(); } }); Writer w = new UTF8OutputStreamWriter(new URLOutputStream(new URL(Utils.toURL("http://localhost:9873/.cucumber"), "stepdefs.json"))); w.write("Hellesøy"); w.flush(); w.close(); assertEquals("Hellesøy", data.poll(1000, TimeUnit.MILLISECONDS)); }
36. TestRestApiAuthorization#setup()
View license@Before public void setup() throws Exception { server = null; baseDir = createTestDir(); log4jConf = new File(baseDir, "log4j.properties").getAbsolutePath(); File logFile = new File(baseDir, "x.log"); Writer writer = new FileWriter(log4jConf); writer.write(LogUtils.LOG4J_APPENDER_STREAMSETS_FILE_PROPERTY + "=" + logFile.getAbsolutePath() + "\n"); writer.write(LogUtils.LOG4J_APPENDER_STREAMSETS_LAYOUT_CONVERSION_PATTERN + "=" + CONVERSION_PATTERN); writer.close(); Assert.assertTrue(new File(baseDir, "etc").mkdir()); Assert.assertTrue(new File(baseDir, "data").mkdir()); Assert.assertTrue(new File(baseDir, "log").mkdir()); Assert.assertTrue(new File(baseDir, "web").mkdir()); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR, baseDir + "/etc"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.DATA_DIR, baseDir + "/data"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.LOG_DIR, baseDir + "/log"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.STATIC_WEB_DIR, baseDir + "/web"); }
37. Program#writeHtmlTestReport()
View licenseprivate static void writeHtmlTestReport() throws Exception { if (Data.reportFilePath == null) return; Log.println("*** Program: Generating tests report: " + Data.reportFilePath); System.out.println(Utils.EOL + "Generated report: \"" + Data.reportFilePath + "\""); if (FileUtils.fileExists(Data.reportFilePath)) FileUtils.deleteFile(Data.reportFilePath); OutputStream reportOutputStream = new FileOutputStream(Data.reportFilePath); Writer reportWriter = new OutputStreamWriter(reportOutputStream); String report = Reporter.generateHtmlReport(Data.testSuiteInfo); reportWriter.write(report); reportWriter.flush(); reportWriter.close(); }
38. Program#writeXmlTestTestSummaryForCcnet()
View licenseprivate static void writeXmlTestTestSummaryForCcnet() throws Exception { if (Data.ccnetSummaryFilePath == null) return; Log.println("*** Program: Generating tests summary for ccnet: " + Data.ccnetSummaryFilePath); if (FileUtils.fileExists(Data.ccnetSummaryFilePath)) FileUtils.deleteFile(Data.ccnetSummaryFilePath); OutputStream summaryOutputStream = new FileOutputStream(Data.ccnetSummaryFilePath); Writer summaryWriter = new OutputStreamWriter(summaryOutputStream); String summary = Reporter.generateXmlSummaryForCCNet(Data.testSuiteInfo); summaryWriter.write(summary); summaryWriter.flush(); summaryWriter.close(); }
39. TomcatNormalScopeProxyFactoryTest#createWar()
View licenseprivate static File createWar(final File test, final Class<?>... classes) throws IOException { for (final Class<?> clazz : classes) { final String name = clazz.getName().replace('.', '/') + ".class"; final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); if (is == null) { throw new IllegalArgumentException(name); } final File out = new File(test, "WEB-INF/classes/" + name); dir(out.getParentFile()); final OutputStream os = new FileOutputStream(out); IOUtils.copy(is, os); is.close(); os.close(); } final Writer w = new FileWriter(new File(test, "WEB-INF/beans.xml")); w.write("<beans />"); w.close(); return test; }
40. IntegrationTestGenerator#openOutput()
View license/** * Opens a {@link Writer} and writes out an appropriate CSV header. * * @param schemaVersion Schema version of the output. This cannot be * <code>null</code>. * @param description Description string used to build the filename. * This cannot be <code>null</code>. * @param type {@link TestType type} of the test file to be written. * This cannot be <code>null</code>. * @return The opened {@link Writer writer}. This will never be <code>null</code>. */ private static Writer openOutput(final ISchemaVersion schemaVersion, final String description, final TestType type) throws IOException { final String schemaVersionPrefix = "v" + schemaVersion.schemaVersionNumber() + "_"; final String header; final String filename; switch(type) { case ADD: header = "cardinality,raw_value,HLL\n"; filename = schemaVersionPrefix + "cumulative_add_" + description + ".csv"; break; case UNION: header = "cardinality,HLL,union_cardinality,union_HLL\n"; filename = schemaVersionPrefix + "cumulative_union_" + description + ".csv"; break; default: throw new RuntimeException("Unknown test type " + type); } final Writer output = Files.newBufferedWriter(Paths.get(OUTPUT_DIRECTORY, filename), StandardCharsets.UTF_8); output.write(header); output.flush(); return output; }
41. IntegrationTestGenerator#globalUnionTest()
View license/** * Unions an EMPTY accumulator with random HLLs. * * Format: cumulative union * Tests: * - hopefully all union possibilities */ private static void globalUnionTest(final ISchemaVersion schemaVersion) throws IOException { final Writer output = openOutput(schemaVersion, "comprehensive", TestType.UNION); // the accumulator, starts empty final HLL hll = newHLL(HLLType.EMPTY); final HLL emptyHLL = newHLL(HLLType.EMPTY); cumulativeUnionLine(output, hll, emptyHLL, schemaVersion); for (int i = 0; i < 1000; /*number of rows to generate*/ i++) { final HLL randomHLL = generateRandomHLL(); cumulativeUnionLine(output, hll, randomHLL, schemaVersion); } output.flush(); output.close(); }
42. IntegrationTestGenerator#probabilisticUnionTest()
View license/** * Unions an EMPTY accumulator with FULL HLLs, each having * many registers set, twice in a row to verify that the set properties are * satisfied. * * Format: cumulative union * Tests: * - EMPTY U FULL * - FULL U FULL */ private static void probabilisticUnionTest(final ISchemaVersion schemaVersion) throws IOException { final Writer output = openOutput(schemaVersion, "probabilistic_probabilistic", TestType.UNION); final Random random = new Random(randomLong()); // the accumulator, starts empty final HLL hll = newHLL(HLLType.EMPTY); final HLL emptyHLL = newHLL(HLLType.EMPTY); cumulativeUnionLine(output, hll, emptyHLL, schemaVersion); for (int i = 0; i < 1000; /*number of rows to generate*/ i++) { // make a FULL set and populate with final HLL fullHLL = newHLL(HLLType.FULL); final int elementCount = random.nextInt(10000); for (int j = 0; j < elementCount; j++) { fullHLL.addRaw(random.nextLong()); } cumulativeUnionLine(output, hll, fullHLL, schemaVersion); } output.flush(); output.close(); }
43. IntegrationTestGenerator#sparseProbabilisticOverlapTest()
View license/** * Unions an EMPTY accumulator with SPARSE HLLs, each * having a single register set, twice in a row to verify that the set * properties are satisfied. * * Format: cumulative union * Tests: * - EMPTY U SPARSE * - SPARSE U SPARSE */ private static void sparseProbabilisticOverlapTest(final ISchemaVersion schemaVersion) throws IOException { final Writer output = openOutput(schemaVersion, "sparse_sparse", TestType.UNION); final Random random = new Random(randomLong()); // the accumulator, starts empty final HLL hll = newHLL(HLLType.EMPTY); final HLL emptyHLL = newHLL(HLLType.EMPTY); cumulativeUnionLine(output, hll, emptyHLL, schemaVersion); for (int i = 0; i < SPARSE_THRESHOLD; i++) { // make a SPARSE set and populate with cardinality 1 final HLL sparseHLL = newHLL(HLLType.SPARSE); final int registerIndex = Math.abs(random.nextInt()) % REGISTER_COUNT; final int registerValue = ((Math.abs(random.nextInt()) % REGISTER_MAX_VALUE) + 1); final long rawValue = constructHLLValue(LOG2M, registerIndex, registerValue); sparseHLL.addRaw(rawValue); cumulativeUnionLine(output, hll, sparseHLL, schemaVersion); } output.flush(); output.close(); }
44. IntegrationTestGenerator#explicitOverlapTest()
View license/** * Unions an EMPTY accumulator with EXPLICIT HLLs, each having a single * random value, twice in a row to verify that the set properties are * satisfied. * * Format: cumulative union * Tests: * - EMPTY U EXPLICIT * - EXPLICIT U EXPLICIT */ private static void explicitOverlapTest(final ISchemaVersion schemaVersion) throws IOException { final Writer output = openOutput(schemaVersion, "explicit_explicit", TestType.UNION); final Random random = new Random(randomLong()); // the accumulator, starts empty final HLL hll = newHLL(HLLType.EMPTY); final HLL emptyHLL = newHLL(HLLType.EMPTY); cumulativeUnionLine(output, hll, emptyHLL, schemaVersion); for (int i = 0; i < EXPLICIT_THRESHOLD; i++) { // make an EXPLICIT set and populate with cardinality 1 final HLL explicitHLL = newHLL(HLLType.EXPLICIT); explicitHLL.addRaw(random.nextLong()); // union it into the accumulator twice, to test overlap (cardinality should not change) cumulativeUnionLine(output, hll, explicitHLL, schemaVersion); cumulativeUnionLine(output, hll, explicitHLL, schemaVersion); } output.flush(); output.close(); }
45. IntegrationTestGenerator#explicitPromotionTest()
View license/** * Unions an EMPTY accumulator with EXPLICIT HLLs, each containing a * single random value. * * Format: cumulative union * Tests: * - EMPTY U EXPLICIT * - EXPLICIT U EXPLICIT * - EXPLICIT to SPARSE promotion * - SPARSE U EXPLICIT */ private static void explicitPromotionTest(final ISchemaVersion schemaVersion) throws IOException { final Writer output = openOutput(schemaVersion, "explicit_promotion", TestType.UNION); final Random random = new Random(randomLong()); // the accumulator, starts empty final HLL hll = newHLL(HLLType.EMPTY); final HLL emptyHLL = newHLL(HLLType.EMPTY); cumulativeUnionLine(output, hll, emptyHLL, schemaVersion); for (int i = 0; i < (EXPLICIT_THRESHOLD + 500); /*should be greater than promotion cutoff*/ i++) { // make an EXPLICIT set and populate with cardinality 1 final HLL explicitHLL = newHLL(HLLType.EXPLICIT); explicitHLL.addRaw(random.nextLong()); cumulativeUnionLine(output, hll, explicitHLL, schemaVersion); } output.flush(); output.close(); }
46. IntegrationTestGenerator#sparseEdgeTest()
View license/** * Cumulatively sets the first register (index 0) to value 2, the last * register (index m-1) to value 2, and then sets registers with indices in * the range 2 to (sparseCutoff + 2) to value 1 to trigger promotion. * * This tests for register alignment in the promotion from SPARSE * to FULL. * * Format: cumulative add * Tests: * - SPARSE addition * - SPARSE to FULL promotion */ private static void sparseEdgeTest(final ISchemaVersion schemaVersion) throws IOException { final Writer output = openOutput(schemaVersion, "sparse_edge", TestType.ADD); // the accumulator, starts empty final HLL hll = newHLL(HLLType.SPARSE); initLineAdd(output, hll, schemaVersion); final long firstValue = constructHLLValue(LOG2M, 0, 2); cumulativeAddLine(output, hll, firstValue, schemaVersion); final long lastValue = constructHLLValue(LOG2M, (1 << LOG2M) - 1, 2); cumulativeAddLine(output, hll, lastValue, schemaVersion); for (int i = 2; i < (SPARSE_THRESHOLD + 2); i++) { final long middleValue = constructHLLValue(LOG2M, i, 1); cumulativeAddLine(output, hll, middleValue, schemaVersion); } output.flush(); output.close(); }
47. IntegrationTestGenerator#sparseRandomTest()
View license/** * Cumulatively sets random registers of a SPARSE HLL to * random values by adding random values. Does not induce promotion. * * Format: cumulative add * Tests: * - SPARSE addition (random) */ private static void sparseRandomTest(final ISchemaVersion schemaVersion) throws IOException { final Writer output = openOutput(schemaVersion, "sparse_random", TestType.ADD); final Random random = new Random(randomLong()); // the accumulator, starts empty final HLL hll = newHLL(HLLType.SPARSE); initLineAdd(output, hll, schemaVersion); for (int i = 0; i < SPARSE_THRESHOLD; i++) { final int registerIndex = Math.abs(random.nextInt()) % REGISTER_COUNT; final int registerValue = ((Math.abs(random.nextInt()) % REGISTER_MAX_VALUE) + 1); final long rawValue = constructHLLValue(LOG2M, registerIndex, registerValue); cumulativeAddLine(output, hll, rawValue, schemaVersion); } output.flush(); output.close(); }
48. IntegrationTestGenerator#sparseStepTest()
View license/** * Cumulatively sets successive registers to: * * <code>(registerIndex % REGISTER_MAX_VALUE) + 1</code> * * by adding specifically constructed values to a SPARSE HLL. * Does not induce promotion. * * Format: cumulative add * Tests: * - SPARSE addition (predictable) */ private static void sparseStepTest(final ISchemaVersion schemaVersion) throws IOException { final Writer output = openOutput(schemaVersion, "sparse_step", TestType.ADD); // the accumulator, starts empty sparse probabilistic final HLL hll = newHLL(HLLType.SPARSE); initLineAdd(output, hll, schemaVersion); for (int i = 0; i < SPARSE_THRESHOLD; i++) { final long rawValue = constructHLLValue(LOG2M, i, ((i % REGISTER_MAX_VALUE) + 1)); cumulativeAddLine(output, hll, rawValue, schemaVersion); } output.flush(); output.close(); }
49. IntegrationTestGenerator#globalStepTest()
View license/** * Cumulatively adds random values to an EMPTY HLL. * * Format: cumulative add * Tests: * - EMPTY, EXPLICIT, SPARSE, PROBABILSTIC addition * - EMPTY to EXPLICIT promotion * - EXPLICIT to SPARSE promotion * - SPARSE to FULL promotion */ private static void globalStepTest(final ISchemaVersion schemaVersion) throws IOException { final Writer output = openOutput(schemaVersion, "comprehensive_promotion", TestType.ADD); // the accumulator, starts empty final HLL hll = newHLL(HLLType.EMPTY); initLineAdd(output, hll, schemaVersion); for (int i = 0; i < 10000; /*arbitrary*/ i++) { cumulativeAddLine(output, hll, randomLong(), schemaVersion); } output.flush(); output.close(); }
50. MorphlineGoLiveMiniMRTest#upAvroFile()
View licenseprivate Path upAvroFile(FileSystem fs, Path inDir, String DATADIR, Path dataDir, String localFile) throws IOException, UnsupportedEncodingException { Path INPATH = new Path(inDir, "input.txt"); OutputStream os = fs.create(INPATH); Writer wr = new OutputStreamWriter(os, StandardCharsets.UTF_8); wr.write(DATADIR + File.separator + localFile); wr.close(); assertTrue(fs.mkdirs(dataDir)); fs.copyFromLocalFile(new Path(DOCUMENTS_DIR, localFile), dataDir); return INPATH; }
51. WroTestUtils#compare()
View license/** * Compare contents of two resources (files) by performing some sort of processing on input resource. * * @param inputResourceUri * uri of the resource to process. * @param expectedContentResourceUri * uri of the resource to compare with processed content. * @param processor * a closure used to process somehow the input content. */ public static void compare(final Reader resultReader, final Reader expectedReader, final ResourcePostProcessor processor) throws IOException { final Writer resultWriter = new StringWriter(); processor.process(resultReader, resultWriter); final Writer expectedWriter = new StringWriter(); IOUtils.copy(expectedReader, expectedWriter); compare(expectedWriter.toString(), resultWriter.toString()); expectedReader.close(); expectedWriter.close(); }
52. MessageBodyWriterIsWritableSet#writeTo()
View license@SuppressWarnings({ "unchecked", "cast" }) public void writeTo(Set arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4, MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException { Writer writer = new OutputStreamWriter(arg6); Set<?> s = (Set<?>) arg0; writer.write("set:"); List list = new ArrayList(s); Collections.sort(list); for (Object o : list) { writer.write(o.toString()); } writer.flush(); }
53. MessageBodyWriterIsWritablePostAnnotated#writeTo()
View licensepublic void writeTo(List arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4, MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException { Writer writer = new OutputStreamWriter(arg6); writer.write("postannotation:"); for (Object o : arg0) { writer.write(o.toString()); } writer.flush(); }
54. MessageBodyWriterIsWritableMediaTypeHashMap#writeTo()
View licensepublic void writeTo(Object arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4, MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException { Writer writer = new OutputStreamWriter(arg6); writer.write("mediatype:"); Map map = (Map) arg0; for (Object k : map.keySet()) { writer.write(k.toString() + "=" + map.get(k)); } writer.flush(); }
55. MessageBodyWriterIsWritableGetAnnotated#writeTo()
View licensepublic void writeTo(Object arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4, MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException { Writer writer = new OutputStreamWriter(arg6); writer.write("getannotation:"); List list = (List) arg0; for (Object o : list) { writer.write(o.toString()); } writer.flush(); }
56. MessageBodyWriterIsWritableGenericEntitySetString#writeTo()
View license@SuppressWarnings("unchecked") public void writeTo(Object arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4, MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException { Writer writer = new OutputStreamWriter(arg6); Set<String> s = (Set<String>) arg0; writer.write("set<string>:"); List<String> list = new ArrayList<String>(s); Collections.sort(list); for (Object o : list) { writer.write(o.toString()); } writer.flush(); }
57. MessageBodyWriterIsWritableGenericEntitySetInteger#writeTo()
View license@SuppressWarnings("unchecked") public void writeTo(Object arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4, MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException { Writer writer = new OutputStreamWriter(arg6); Set<Integer> s = (Set<Integer>) arg0; writer.write("set<integer>:"); List<Integer> list = new ArrayList<Integer>(s); Collections.sort(list); for (Object o : list) { writer.write(o.toString()); } writer.flush(); }
58. MessageBodyWriterIsWritableClassDeque#writeTo()
View licensepublic void writeTo(Object arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4, MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException, WebApplicationException { Writer writer = new OutputStreamWriter(arg6); Deque d = (Deque) arg0; writer.write("deque:"); for (Object o : d) { writer.write(o.toString()); } writer.flush(); }
59. DataSourceResourceLoaderTestCase#testUnicode()
View licensepublic void testUnicode() throws Exception { Template template = RuntimeSingleton.getTemplate(UNICODE_TEMPLATE_NAME); Writer writer = new StringWriter(); VelocityContext context = new VelocityContext(); template.merge(context, writer); writer.flush(); writer.close(); String outputText = writer.toString(); if (!normalizeNewlines(UNICODE_TEMPLATE).equals(normalizeNewlines(outputText))) { fail("Output incorrect for Template: " + UNICODE_TEMPLATE_NAME); } }
60. SetTestCase#checkTemplate()
View licensepublic void checkTemplate(String templateName) throws Exception { Template template; FileOutputStream fos; Writer fwriter; template = engine.getTemplate(getFileName(null, templateName, TMPL_FILE_EXT)); fos = new FileOutputStream(getFileName(RESULTS_DIR, templateName, RESULT_FILE_EXT)); fwriter = new BufferedWriter(new OutputStreamWriter(fos)); template.merge(context, fwriter); fwriter.flush(); fwriter.close(); if (!isMatch(RESULTS_DIR, COMPARE_DIR, templateName, RESULT_FILE_EXT, CMP_FILE_EXT)) { fail("Output incorrect."); } }
61. ResourceCachingTestCase#testIncludeParseCaching()
View license/** * Tests for fix of bug VELOCITY-98 where a #include followed by #parse * of the same file throws ClassCastException when caching is on. * @throws Exception */ public void testIncludeParseCaching() throws Exception { VelocityEngine ve = new VelocityEngine(); ve.setProperty("file.resource.loader.cache", "true"); ve.setProperty("file.resource.loader.path", TemplateTestBase.TEST_COMPARE_DIR + FILE_RESOURCE_LOADER_PATH); ve.init(); Template template = ve.getTemplate("testincludeparse.vm"); Writer writer = new StringWriter(); VelocityContext context = new VelocityContext(); // will produce a ClassCastException if Velocity-98 is not solved template.merge(context, writer); writer.flush(); writer.close(); }
62. CmsJspLoader#showSource()
View license/** * Delivers the plain uninterpreted resource with escaped XML.<p> * * This is intended for viewing historical versions.<p> * * @param cms the initialized CmsObject which provides user permissions * @param file the requested OpenCms VFS resource * @param req the servlet request * @param res the servlet response * * @throws IOException might be thrown by the servlet environment * @throws CmsException in case of errors accessing OpenCms functions */ protected void showSource(CmsObject cms, CmsResource file, HttpServletRequest req, HttpServletResponse res) throws CmsException, IOException { CmsResource historyResource = (CmsResource) CmsHistoryResourceHandler.getHistoryResource(req); if (historyResource == null) { historyResource = file; } CmsFile historyFile = cms.readFile(historyResource); String content = new String(historyFile.getContents()); // change the content-type header so that browsers show plain text res.setContentLength(content.length()); res.setContentType("text/plain"); Writer out = res.getWriter(); out.write(content); out.close(); }
63. UnicodeWriterTest#test()
View license@Test public void test() throws IOException { File file = new File("target/unicodeWriterTest.txt"); Writer writer = new UnicodeWriter(file, "UTF-8"); writer.write("Hello"); writer.close(); FileInputStream is = new FileInputStream(file); byte[] bytes = new byte[100]; assertEquals(8, is.read(bytes)); assertEquals(UnicodeWriter.UTF8_BOM[0], bytes[0]); assertEquals(UnicodeWriter.UTF8_BOM[1], bytes[1]); assertEquals(UnicodeWriter.UTF8_BOM[2], bytes[2]); assertEquals((byte) 'H', bytes[3]); is.close(); }
64. SimpleMailboxMembership#getHeaderContent()
View license/** * @see org.apache.james.mailbox.store.mail.model.Message#getHeaderContent() */ public InputStream getHeaderContent() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final Writer writer = new OutputStreamWriter(baos, "us-ascii"); Iterator<Entry<String, String>> hIt = headers.entrySet().iterator(); while (hIt.hasNext()) { Entry<String, String> header = hIt.next(); writer.write(header.getKey()); writer.write(": "); writer.write(header.getValue()); writer.write(NEW_LINE); } writer.write(NEW_LINE); writer.flush(); return new ByteArrayInputStream(baos.toByteArray()); }
65. CNDSerializer#writeContent()
View license/** * {@inheritDoc} */ public void writeContent(OutputStream out) throws IOException, RepositoryException { Writer w = new OutputStreamWriter(out, "utf-8"); for (String prefix : aggregate.getNamespacePrefixes()) { w.write("<'"); w.write(prefix); w.write("'='"); w.write(escape(aggregate.getNamespaceURI(prefix))); w.write("'>\n"); } w.write("\n"); writeNodeTypeDef(w, aggregate.getNode()); w.close(); out.flush(); }
66. OldWriterTest#test_writeI()
View licensepublic void test_writeI() throws IOException { Writer tobj = new Support_ASimpleWriter(2); tobj.write('a'); tobj.write('b'); assertEquals("Wrong stuff written!", "ab", tobj.toString()); try { tobj.write('c'); fail("IOException not thrown!"); } catch (IOException e) { } }
67. CheckinEngine#createTempFileForSymbolicLink()
View license/** * Creates a temporary file for symbolic links to work with before * uploading. * * @param change * The PendingChange that is being filtered * @return A string representing the temporary file we created * @throws IOException * If the file could not be created */ private String createTempFileForSymbolicLink(final String localItem, final String targetLink) throws IOException { final String tempFile = TempStorageService.getInstance().createTempFile().getAbsolutePath(); //$NON-NLS-1$ log.trace(MessageFormat.format("Using temporary file {0} for symbolic link {1}", tempFile, localItem)); final Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile))); out.write(targetLink); out.close(); log.trace(MessageFormat.format(//$NON-NLS-1$ "Symbolic link target {0} written to temporary file {1} as contents", targetLink, tempFile)); return tempFile; }
68. JSONIntegrationTest#testPOJOServiceWithJSONBadgerfish()
View license@Test public void testPOJOServiceWithJSONBadgerfish() throws Exception { HttpURLConnection conn = (HttpURLConnection) new URL(server.getEndpoint("POJOService")).openConnection(); conn.setDoOutput(true); conn.addRequestProperty("Content-Type", "application/json/badgerfish"); Writer out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // XML is: <sayHello xmlns="http://example.org"><myName>Joe</myName></sayHello> out.write("{ \"sayHello\" : { \"@xmlns\" : { \"$\" : \"http://example.org\" }, \"myName\" : { \"$\" : \"Joe\" } } }"); out.close(); assertEquals(200, conn.getResponseCode()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); assertTrue(in.readLine().contains("Hello Joe!")); in.close(); }
69. JSONIntegrationTest#testPOJOServiceWithJSONMapped()
View license@Test public void testPOJOServiceWithJSONMapped() throws Exception { HttpURLConnection conn = (HttpURLConnection) new URL(server.getEndpoint("POJOService")).openConnection(); conn.setDoOutput(true); conn.addRequestProperty("Content-Type", "application/json"); Writer out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); out.write("{ \"sayHello\" : { \"myName\" : \"Joe\" } }"); out.close(); assertEquals(200, conn.getResponseCode()); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); assertEquals("{\"sayHelloResponse\":{\"return\":\"Hello Joe!\"}}", in.readLine()); in.close(); }
70. XcodeprojGeneration#write()
View license/** * Writes a project to an {@code OutputStream} in the correct encoding. */ public static void write(OutputStream out, PBXProject project) throws IOException { XcodeprojSerializer ser = new XcodeprojSerializer(new GidGenerator(ImmutableSet.<String>of()), project); Writer outWriter = new OutputStreamWriter(out, StandardCharsets.UTF_8); // toXMLPropertyList includes an XML encoding specification (UTF-8), which we specify above. // Standard Xcodeproj files use the toASCIIPropertyList format, but Xcode will rewrite // XML-encoded project files automatically when first opening them. We use XML to prevent // encoding issues, since toASCIIPropertyList does not include the UTF-8 encoding comment, and // Xcode by default apparently uses MacRoman. // This encoding concern is probably why Buck also generates XML project files as well. outWriter.write(ser.toPlist().toXMLPropertyList()); outWriter.flush(); }
71. Driver#writeWeather()
View licenseprivate void writeWeather(Location location, List<WeatherRecord> trajectory) throws Exception { File outputFile = new File(outputDir.toString() + File.separator + location.getZipcode() + ".txt"); Writer output = new BufferedWriter(new FileWriter(outputFile)); output.write("date,city,state,zipcode,temperature,windchill,windspeed,precipitation,rainfall,snowfall\n"); for (WeatherRecord weather : trajectory) { String record = weather.getDate() + ","; record += location.getCity() + ","; record += location.getState() + ","; record += location.getZipcode() + ","; record += weather.getTemperature() + ","; record += weather.getWindChill() + ","; record += weather.getWindSpeed() + ","; record += weather.getPrecipitation() + ","; record += weather.getRainFall() + ","; record += weather.getSnowFall() + "\n"; output.write(record); } output.close(); }
72. SMTPClient#sendShortMessageData()
View license/*** * A convenience method for sending short messages. This method fetches * the Writer returned by {@link #sendMessageData sendMessageData() } * and writes the specified String to it. After writing the message, * this method calls {@link #completePendingCommand completePendingCommand() } * to finalize the transaction and returns * its success or failure. * <p> * @param message The short email message to send. * This must include the headers and the body, but not the trailing "." * @return True if successfully completed, false if not. * @throws SMTPConnectionClosedException * If the SMTP server prematurely closes the connection as a result * of the client being idle or some other reason causing the server * to send SMTP reply code 421. This exception may be caught either * as an IOException or independently as itself. * @throws IOException If an I/O error occurs while either sending a * command to the server or receiving a reply from the server. ***/ public boolean sendShortMessageData(String message) throws IOException { Writer writer; writer = sendMessageData(); if (writer == null) { return false; } writer.write(message); writer.close(); return completePendingCommand(); }
73. LexicalizedParserClient#getTokenizedText()
View license/** * Tokenize the text according to the parser's tokenizer, * return it as whitespace tokenized text. */ public String getTokenizedText(String query) throws IOException { Socket socket = new Socket(host, port); Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8"); out.write("tokenize " + query + "\n"); out.flush(); String result = readResult(socket); socket.close(); return result; }
74. LexicalizedParserClient#getLemmas()
View license/** * Get the lemmas for the text according to the parser's lemmatizer * (only applies to English), return it as whitespace tokenized text. */ public String getLemmas(String query) throws IOException { Socket socket = new Socket(host, port); Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8"); out.write("lemma " + query + "\n"); out.flush(); String result = readResult(socket); socket.close(); return result; }
75. LexicalizedParserClient#getDependencies()
View license/** * Returns the String output of the dependencies. * <br> * TODO: use some form of Mode enum (such as the one in SemanticGraphFactory) * instead of a String */ public String getDependencies(String query, String mode) throws IOException { Socket socket = new Socket(host, port); Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8"); out.write("dependencies:" + mode + " " + query + "\n"); out.flush(); String result = readResult(socket); socket.close(); return result; }
76. LexicalizedParserClient#getParse()
View license/** * Returns the String output of the parse of the given query. * <br> * The "parse" method in the server is mostly useful for clients * using a language other than Java who don't want to import or wrap * Tree in any way. However, it is useful to provide getParse to * test that functionality in the server. */ public String getParse(String query, boolean binarized) throws IOException { Socket socket = new Socket(host, port); Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8"); out.write("parse" + (binarized ? ":binarized " : " ") + query + "\n"); out.flush(); String result = readResult(socket); socket.close(); return result; }
77. LexicalizedParserClient#getTree()
View license/** * Returs a Tree from the server connected to at host:port. */ public Tree getTree(String query) throws IOException { Socket socket = new Socket(host, port); Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8"); out.write("tree " + query + "\n"); out.flush(); ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); Object o; try { o = ois.readObject(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } if (!(o instanceof Tree)) { throw new IllegalArgumentException("Expected a tree"); } Tree tree = (Tree) o; socket.close(); return tree; }
78. URLOutputStreamTest#write_to_file_without_existing_parent_directory()
View license@Test public void write_to_file_without_existing_parent_directory() throws IOException, URISyntaxException { Path filesWithoutParent = Files.createTempDirectory("filesWithoutParent"); String baseURL = filesWithoutParent.toUri().toURL().toString(); URL urlWithoutParentDirectory = new URL(baseURL + "/non/existing/directory"); Writer w = new UTF8OutputStreamWriter(new URLOutputStream(urlWithoutParentDirectory)); w.write("Hellesøy"); w.close(); File testFile = new File(urlWithoutParentDirectory.toURI()); assertEquals("Hellesøy", FixJava.readReader(openUTF8FileReader(testFile))); }
79. URLOutputStreamTest#throws_ioe_if_http_response_is_500()
View license@Test public void throws_ioe_if_http_response_is_500() throws IOException, ExecutionException, InterruptedException { Rest r = new Rest(webbit); r.PUT("/.cucumber/stepdefs.json", new HttpHandler() { @Override public void handleHttpRequest(HttpRequest req, HttpResponse res, HttpControl ctl) throws Exception { res.status(500); res.content("something went wrong"); res.end(); } }); Writer w = new UTF8OutputStreamWriter(new URLOutputStream(new URL(Utils.toURL("http://localhost:9873/.cucumber"), "stepdefs.json"))); w.write("Hellesøy"); w.flush(); try { w.close(); fail(); } catch (IOException expected) { assertEquals("PUT http://localhost:9873/.cucumber/stepdefs.json\n" + "HTTP 500\nsomething went wrong", expected.getMessage()); } }
80. TestRestApiAuthorization#startServer()
View licenseprivate String startServer(boolean authzEnabled) throws Exception { int port = NetworkUtils.getRandomPort(); Configuration conf = new Configuration(); conf.set(WebServerTask.HTTP_PORT_KEY, port); conf.set(WebServerTask.AUTHENTICATION_KEY, (authzEnabled) ? "basic" : "none"); Writer writer = new FileWriter(new File(System.getProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR), "sdc.properties")); conf.save(writer); writer.close(); File realmFile = new File(System.getProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR), "basic-realm.properties"); writer = new FileWriter(realmFile); IOUtils.copy(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("basic-realm.properties")), writer); writer.close(); Files.setPosixFilePermissions(realmFile.toPath(), WebServerTask.OWNER_PERMISSIONS); ObjectGraph dagger = ObjectGraph.create(MainStandalonePipelineManagerModule.class); RuntimeInfo runtimeInfo = dagger.get(RuntimeInfo.class); runtimeInfo.setAttribute(RuntimeInfo.LOG4J_CONFIGURATION_URL_ATTR, new URL("file://" + baseDir + "/log4j.properties")); server = dagger.get(TaskWrapper.class); server.init(); server.run(); return "http://127.0.0.1:" + port; }
81. DiskLruCacheTest#openWithTruncatedLineDiscardsThatLine()
View license@Test public void openWithTruncatedLineDiscardsThatLine() throws Exception { cache.close(); writeFile(getCleanFile("k1", 0), "A"); writeFile(getCleanFile("k1", 1), "B"); Writer writer = new FileWriter(journalFile); // no trailing newline writer.write(MAGIC + "\n" + VERSION_1 + "\n100\n2\n\nCLEAN k1 1 1"); writer.close(); cache = DiskLruCache.open(cacheDir, appVersion, 2, Integer.MAX_VALUE); assertThat(cache.get("k1")).isNull(); // The journal is not corrupt when editing after a truncated line. set("k1", "C", "D"); cache.close(); cache = DiskLruCache.open(cacheDir, appVersion, 2, Integer.MAX_VALUE); assertValue("k1", "C", "D"); }
82. RESTServiceTest#putFailAgainstCollection()
View license@Test public void putFailAgainstCollection() throws IOException { HttpURLConnection connect = getConnection(COLLECTION_URI); connect.setRequestProperty("Authorization", "Basic " + credentials); connect.setRequestMethod("PUT"); connect.setDoOutput(true); connect.setRequestProperty("ContentType", "application/xml"); Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8"); writer.write(XML_DATA); writer.close(); connect.connect(); int r = connect.getResponseCode(); assertEquals("Server returned response code " + r, 400, r); }
83. RESTServiceTest#xqueryGetFailWithNonEmptyPath()
View license@Test public void xqueryGetFailWithNonEmptyPath() throws IOException { /* store the documents that we need for this test */ HttpURLConnection sconnect = getConnection(RESOURCE_URI); sconnect.setRequestProperty("Authorization", "Basic " + credentials); sconnect.setRequestMethod("PUT"); sconnect.setDoOutput(true); sconnect.setRequestProperty("ContentType", "application/xml"); Writer writer = new OutputStreamWriter(sconnect.getOutputStream(), "UTF-8"); writer.write(XML_DATA); writer.close(); // should not be able to get this path String path = RESOURCE_URI + "/some/path"; HttpURLConnection connect = getConnection(path); connect.setRequestMethod("GET"); connect.connect(); int r = connect.getResponseCode(); assertEquals("Server returned response code " + r, 404, r); }
84. NodeListModel#main()
View license/** * Loads a template from a file passed as the first argument, loads an XML * document from the standard input, passes it to the template as variable * <tt>document</tt> and writes the result of template processing to * standard output. * * @deprecated Will be removed (main method in a library, often classified as CWE-489 "Leftover Debug Code"). */ @Deprecated public static void main(String[] args) throws Exception { org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(); Document document = builder.build(System.in); SimpleHash model = new SimpleHash(); model.put("document", new NodeListModel(document)); FileReader fr = new FileReader(args[0]); Template template = new Template(args[0], fr); Writer w = new java.io.OutputStreamWriter(System.out); template.process(model, w); w.flush(); w.close(); }
85. RestApiServlet#replyJson()
View licensepublic static long replyJson(@Nullable HttpServletRequest req, HttpServletResponse res, Multimap<String, String> config, Object result) throws IOException { TemporaryBuffer.Heap buf = heap(HEAP_EST_SIZE, Integer.MAX_VALUE); buf.write(JSON_MAGIC); Writer w = new BufferedWriter(new OutputStreamWriter(buf, UTF_8)); Gson gson = newGson(config, req); if (result instanceof JsonElement) { gson.toJson((JsonElement) result, w); } else { gson.toJson(result, w); } w.write('\n'); w.flush(); return replyBinaryResult(req, res, asBinaryResult(buf).setContentType(JSON_TYPE).setCharacterEncoding(UTF_8)); }
86. CTB2CONLL#clean()
View license/** * ?ctb????????????????????????????? * @param file ??? * @throws IOException * ??5:34:24 */ private static void clean(String file) throws IOException { StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName("utf8"))); String str; while ((str = br.readLine()) != null) { if (str.length() != 0 && !str.trim().startsWith("<")) { if (str.equalsIgnoreCase("root")) continue; if (str.contains("</HEADER> ") || str.contains("</HEADLINE>")) continue; sb.append(str + "\n"); } } br.close(); Writer wr = new //???? OutputStreamWriter(//???? new FileOutputStream(new File(file)), //???? Charset.forName("gbk")); wr.write(sb.toString()); wr.close(); }
87. TestReportEvent#testHierarchicalMerge()
View license/** * Test that hierarchical merge works correctly - a) that all metrics are * merged in correctly, b) that metrics are renamed correctly and c) that * merged-in metrics with an existing name are suppressed. */ @Test public void testHierarchicalMerge() throws IOException { ReportEvent e1 = new ReportEvent("test"); e1.setLongMetric("another", 12345); e1.setLongMetric("duplicateLong", 23456); long attrs = e.getNumMetrics(); System.out.println("- before merge, " + attrs + " attributes"); Writer out = new OutputStreamWriter(System.out); e.toJson(out); out.flush(); System.out.println("- after merge, " + attrs + " + 2 metrics"); e.hierarchicalMerge("event1", e1); e.toJson(out); out.flush(); assertEquals(attrs + 2, e.getNumMetrics()); assertEquals(e.getLongMetric("event1.another"), Long.valueOf(12345L)); assertEquals(e.getLongMetric("event1.duplicateLong"), Long.valueOf(54321L)); }
88. OldWriterTest#test_appendChar()
View licensepublic void test_appendChar() throws IOException { Writer tobj = new Support_ASimpleWriter(2); tobj.append('a'); tobj.append('b'); assertEquals("Wrong stuff written!", "ab", tobj.toString()); try { tobj.append('c'); fail("IOException not thrown!"); } catch (IOException e) { } }
89. TestReportEvent#testMerge()
View license/** * Only the new "another" attribute should be added to the original report */ @Test public void testMerge() throws IOException { ReportEvent e1 = new ReportEvent("test"); e1.setLongMetric("another", 12345); long attrs = e.getNumMetrics(); System.out.println("- before merge, " + attrs + " attributes"); Writer out = new OutputStreamWriter(System.out); e.toJson(out); out.flush(); System.out.println("- after merge, " + attrs + " + 1 attributes"); e.merge(e1); e.toJson(out); out.flush(); assertEquals(attrs + 1, e.getNumMetrics()); }
90. RESTServiceTest#uploadDataPlus()
View licenseprivate int uploadDataPlus() throws IOException { HttpURLConnection connect = getConnection(RESOURCE_URI_PLUS); connect.setRequestProperty("Authorization", "Basic " + credentials); connect.setRequestMethod("PUT"); connect.setDoOutput(true); connect.setRequestProperty("ContentType", "application/xml"); Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8"); writer.write(XML_DATA); writer.close(); connect.connect(); return connect.getResponseCode(); }
91. RESTServiceTest#preparePost()
View licenseprivate HttpURLConnection preparePost(String content, String path) throws IOException { HttpURLConnection connect = getConnection(path); connect.setRequestProperty("Authorization", "Basic " + credentials); connect.setRequestMethod("POST"); connect.setDoOutput(true); connect.setRequestProperty("Content-Type", "application/xml"); Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8"); writer.write(content); writer.close(); return connect; }
92. RESTServiceTest#putWithCharset()
View license@Test public void putWithCharset() throws IOException { HttpURLConnection connect = getConnection(RESOURCE_URI); connect.setRequestProperty("Authorization", "Basic " + credentials); connect.setRequestMethod("PUT"); connect.setDoOutput(true); connect.setRequestProperty("ContentType", "application/xml; charset=UTF-8"); Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8"); writer.write(XML_DATA); writer.close(); connect.connect(); int r = connect.getResponseCode(); assertEquals("Server returned response code " + r, 201, r); doGet(); }
93. RESTServiceTest#putAgainstXQuery()
View license@Test public void putAgainstXQuery() throws IOException { doPut(TEST_XQUERY_WITH_PATH_AND_CONTENT, "requestwithcontent.xq", 201); String path = COLLECTION_URI_REDIRECTED + "/requestwithcontent.xq/a/b/c"; HttpURLConnection connect = getConnection(path); connect.setRequestProperty("Authorization", "Basic " + credentials); connect.setRequestMethod("PUT"); connect.setDoOutput(true); connect.setRequestProperty("ContentType", "application/xml"); Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8"); writer.write("<data>test data</data>"); writer.close(); connect.connect(); int r = connect.getResponseCode(); assertEquals("doPut: Server returned response code " + r, 200, r); //get the response of the query String response = readResponse(connect.getInputStream()); assertEquals(response.trim(), "test data /a/b/c"); }
94. RESTServiceTest#uploadData()
View licenseprivate int uploadData() throws IOException { HttpURLConnection connect = getConnection(RESOURCE_URI); connect.setRequestProperty("Authorization", "Basic " + credentials); connect.setRequestMethod("PUT"); connect.setDoOutput(true); connect.setRequestProperty("ContentType", "application/xml"); Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8"); writer.write(XML_DATA); writer.close(); connect.connect(); return connect.getResponseCode(); }
95. RESTServiceTest#doPut()
View licenseprivate void doPut(String data, String path, int responseCode) throws IOException { HttpURLConnection connect = getConnection(COLLECTION_URI + '/' + path); connect.setRequestProperty("Authorization", "Basic " + credentials); connect.setRequestMethod("PUT"); connect.setDoOutput(true); connect.setRequestProperty("ContentType", "application/xquery"); Writer writer = new OutputStreamWriter(connect.getOutputStream(), "UTF-8"); writer.write(data); writer.close(); connect.connect(); int r = connect.getResponseCode(); assertEquals("doPut: Server returned response code " + r, responseCode, r); }
96. WriterRepresentation#write()
View license@Override public void write(OutputStream outputStream) throws IOException { Writer writer = null; if (getCharacterSet() != null) { writer = new OutputStreamWriter(outputStream, getCharacterSet().getName()); } else { // Use the default HTTP character set writer = new OutputStreamWriter(outputStream, CharacterSet.UTF_8.getName()); } write(writer); writer.flush(); }
97. JobFailureAndKillHandlerLogicTask#executeTask()
View license/** * {@inheritDoc} */ @Override public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException { log.debug("Executing JobKillLogic Task in the workflow."); final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY); // Append logic for handling job kill signal writer.write(JobConstants.JOB_FAILURE_AND_KILL_HANDLER_LOGIC + System.lineSeparator()); }
98. FilterController#saveConditions()
View licensevoid saveConditions(final DefaultComboBoxModel filterConditionModel, final String pathToFilterFile) throws IOException { final XMLElement saver = new XMLElement(); saver.setName("filter_conditions"); final Writer writer = new FileWriter(pathToFilterFile); for (int i = 0; i < filterConditionModel.getSize(); i++) { final ASelectableCondition cond = (ASelectableCondition) filterConditionModel.getElementAt(i); if (cond != null && !(cond instanceof NoFilteringCondition)) { cond.toXml(saver); } } final XMLWriter xmlWriter = new XMLWriter(writer); xmlWriter.write(saver, true); writer.close(); }
99. MergeSFS#main()
View license/** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length < 2 || args.length > 3) { System.out.println("Merges changes made in a SFS override file to a SFS source file."); System.out.println("Usage: source-file override-file [--stdout]"); System.out.println(" By default the merged file is written to source-file."); System.out.println(" --stdout writes to standard output instead."); return; } File f1 = new File(args[0]); File f2 = new File(args[1]); SimpleFieldSet fs1 = SimpleFieldSet.readFrom(f1, false, true); SimpleFieldSet fs2 = SimpleFieldSet.readFrom(f2, false, true); fs1.putAllOverwrite(fs2); // Force output to UTF-8. A PrintStream is still an OutputStream. // These files are always UTF-8, and stdout is likely to be redirected into one. final OutputStream os; if (args.length == 3 && args[2].equals("--stdout")) { os = System.out; } else { os = new FileOutputStream(f1); } Writer w = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); fs1.writeToOrdered(w); w.flush(); }
100. HTMLFilter#readFilter()
View license@Override public void readFilter(InputStream input, OutputStream output, String charset, HashMap<String, String> otherParams, FilterCallback cb) throws DataFilterException, IOException { if (cb == null) cb = new NullFilterCallback(); logMINOR = Logger.shouldLog(LogLevel.MINOR, this); logDEBUG = Logger.shouldLog(LogLevel.DEBUG, this); if (logMINOR) Logger.minor(this, "readFilter(): charset=" + charset); Reader r = null; Writer w = null; InputStreamReader isr = null; OutputStreamWriter osw = null; try { isr = new InputStreamReader(input, charset); osw = new OutputStreamWriter(output, charset); r = new BufferedReader(isr, 4096); w = new BufferedWriter(osw, 4096); } catch (UnsupportedEncodingException e) { throw UnknownCharsetException.create(e, charset); } HTMLParseContext pc = new HTMLParseContext(r, w, charset, cb, false); pc.run(); w.flush(); }