private String withLineNumbers(String code) { try { return CharStreams.readLines(new StringReader(code), new LineProcessor<String>() { private final StringBuilder lines = new StringBuilder(); private int lineNo = 1; @Override public boolean processLine(String line) throws IOException { lines.append(Strings.padStart(String.valueOf(lineNo++), 3, ' ')).append(": ").append(line) .append("\n"); return true; } @Override public String getResult() { return lines.toString(); } }); } catch (IOException e) { throw new IllegalStateException(e.getMessage()); } }
/** * Helper method to verify that the files were archived correctly by reading {@code * tarArchiveInputStream}. */ private void verifyTarArchive(TarArchiveInputStream tarArchiveInputStream) throws IOException { // Verifies fileA was archived correctly. TarArchiveEntry headerFileA = tarArchiveInputStream.getNextTarEntry(); Assert.assertEquals("some/path/to/resourceFileA", headerFileA.getName()); String fileAString = CharStreams.toString(new InputStreamReader(tarArchiveInputStream, StandardCharsets.UTF_8)); Assert.assertEquals(expectedFileAString, fileAString); // Verifies fileB was archived correctly. TarArchiveEntry headerFileB = tarArchiveInputStream.getNextTarEntry(); Assert.assertEquals("crepecake", headerFileB.getName()); String fileBString = CharStreams.toString(new InputStreamReader(tarArchiveInputStream, StandardCharsets.UTF_8)); Assert.assertEquals(expectedFileBString, fileBString); // Verifies directoryA was archived correctly. TarArchiveEntry headerDirectoryA = tarArchiveInputStream.getNextTarEntry(); Assert.assertEquals("some/path/to/", headerDirectoryA.getName()); Assert.assertNull(tarArchiveInputStream.getNextTarEntry()); }
public TextFileContentProvider ( final File file ) throws FileNotFoundException, IOException { try ( FileReader reader = new FileReader ( file ) ) { if ( file != null ) { String data = CharStreams.toString ( reader ); if ( needFix () ) { data = fix ( data ); } this.data = data.getBytes ( StandardCharsets.UTF_8 ); } else { this.data = null; } } }
@Test public void testReadEverythingMarkReset() throws Exception { Buffer buffer = new Buffer(); PrintStream stream = new PrintStream(buffer.write()); stream.print("0123456789012345678901234567890123456789"); InputStream read = buffer.read(); read.mark(0); assertThat(CharStreams.toString(new InputStreamReader(read))).isEqualTo( "0123456789012345678901234567890123456789"); read.reset(); assertThat(CharStreams.toString(new InputStreamReader(read))).isEqualTo( "0123456789012345678901234567890123456789"); read.reset(); assertThat(CharStreams.toString(new InputStreamReader(read))).isEqualTo( "0123456789012345678901234567890123456789"); }
void map(@NonNull HttpConfiguration httpConfiguration) throws IOException { org.springframework.core.io.Resource[] resources; try { resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources( applicationProperties.getResourcePath() + "/openapi/**.y*ml"); } catch (FileNotFoundException exp) { LOG.warn("No Open API resources found in path:{}/openapi", applicationProperties.getResourcePath()); return; } for (org.springframework.core.io.Resource resource : resources) { InputStream inputStream = new EnvironmentAwareResource(resource.getInputStream(), environment).getInputStream(); String result = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); if (!StringUtils.isBlank(result)) { Swagger swagger = openApiParser.parse(result); mapOpenApiDefinition(swagger, httpConfiguration); } } }
@Override public String readTextFileAttachmentWithEncoding(AttachmentScriptType attachment, String encoding) { if( attachment != null ) { String type = attachment.getType(); if( type.equals(AttachmentType.FILE.toString()) || type.equals(AttachmentType.IMSRES.toString()) || type.equals(AttachmentType.HTML.toString()) ) { final String filename = attachment.getFilename(); try( Reader reader = new UnicodeReader(fileSystem.read(staging, filename), encoding) ) { StringWriter writer = new StringWriter(); CharStreams.copy(reader, writer); return writer.toString(); } catch( IOException io ) { throw new RuntimeException("Error reading text file attachment " + filename, io); } } throw new RuntimeException("Cannot read an attachment of this type as text"); } return null; }
@Override public void sendGrade(ImsxPOXEnvelopeType envelope, String consumerKey, String secret, String url, HttpServletResponse servletResponse) { if( url != null ) { try { final Request req = createLtiOutcomesRequest(envelope, url, consumerKey, secret); try( Response httpResp = httpService.getWebContent(req, configService.getProxyDetails()) ) { parseError(httpResp, url); String respBody = httpResp.getBody(); final String bodyHash = calcSha1Hash(respBody); final OAuthMessage message = createLaunchParameters(consumerKey, secret, url, bodyHash); servletResponse.addHeader("Authorization", message.getAuthorizationHeader("")); CharStreams.copy(new StringReader(httpResp.getBody()), servletResponse.getWriter()); } } catch( Exception e ) { throw Throwables.propagate(e); } } }
@Override public String getStylesheetContents() { final PublicFile styles = new PublicFile("htmleditorstyles"); final HtmlEditorConfiguration editorConfig = getEditorConfig(); final String filename = (Check.isEmpty(editorConfig.getStylesheetUuid()) ? "styles.css" : PathUtils.filePath( editorConfig.getStylesheetUuid(), "styles.css")); if( fileSystemService.fileExists(styles, filename) ) { try (InputStream in = fileSystemService.read(styles, filename); Reader rdr = new InputStreamReader(in)) { final StringWriter sw = new StringWriter(); CharStreams.copy(rdr, sw); return sw.toString(); } catch( IOException e ) { throw Throwables.propagate(e); } } return ""; }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String content; try { content = responseCache.get("", cacheLoader); } catch( ExecutionException e ) { resp.setStatus(500); LOGGER.error("Error serving content", e); return; } if( NO_CONTENT.equals(content) ) { resp.setStatus(404); } else { resp.setContentType("text/plain"); resp.setStatus(200); CharStreams.copy(new StringReader(content), resp.getWriter()); } }
@Override public Set<String> get() { try { try (InputStream inputStream = getClass().getResourceAsStream("SQL_RESERVED_WORDS.txt")) { if (inputStream == null) { throw new RuntimeException("Could not find resource: [SQL_RESERVED_WORDS.txt] near [" + getClass() + "]"); } InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8"); HashSet<String> sqlReservedWords = Sets.newHashSet(Splitter.on("\r\n").split(CharStreams.toString(streamReader))); // temporary removal of words we currently have to allow sqlReservedWords.remove("TYPE"); // DB2 sqlReservedWords.remove("OPERATION"); // DB2, SQL Server "future", PostGres sqlReservedWords.remove("METHOD"); // PostGres sqlReservedWords.remove("LANGUAGE"); // DB2, ODBC (?), SQL Server "future", PostGres sqlReservedWords.remove("LOCATION"); // PostGres sqlReservedWords.remove("YEAR"); // DB2, ODBC (?), SQL Server "future", PostGres sqlReservedWords.remove("DAY"); // DB2, ODBC (?), SQL Server "future", PostGres sqlReservedWords.remove("SECURITY"); // DB2, PostGres return ImmutableSet.copyOf(sqlReservedWords); } } catch (IOException e) { throw new RuntimeException("Failed to load [SQL_RESERVED_WORDS.txt]", e); } }
@Nullable private String loadText(StagingFile stagingFile, String file) throws InvalidHtmlEditorPluginException { if( fileSystemService.fileExists(stagingFile, file) ) { try( final UnicodeReader reader = new UnicodeReader(fileSystemService.read(stagingFile, file), "UTF-8") ) { final StringWriter sw = new StringWriter(); CharStreams.copy(reader, sw); return sw.toString(); } catch( IOException io ) { throw Throwables.propagate(io); } } return null; }
@Nullable private String doGetItem(String uuid, String version, String info) { final Request request = createRequest("item/" + uuid + '/' + version + '/'); request.addParameter("info", info); try( Response response = httpService.getWebContent(request, configService.getProxyDetails()) ) { if( response.isOk() ) { StringWriter sw = new StringWriter(); CharStreams.copy(new InputStreamReader(response.getInputStream()), sw); return sw.toString(); } else if( response.getCode() == 404 ) { return null; } throw new RuntimeException("Unable to query cloud item: " + response.getMessage()); } catch( IOException io ) { throw Throwables.propagate(io); } }
private String doFacetSearchQuery(String... nodes) { final Request request = createRequest("search/facet"); request.addParameter("nodes", Joiner.on(',').join(nodes)); request.addParameter("breadth", 200); try( Response response = httpService.getWebContent(request, configService.getProxyDetails()) ) { if( response.isOk() ) { StringWriter sw = new StringWriter(); CharStreams.copy(new InputStreamReader(response.getInputStream()), sw); return sw.toString(); } throw new RuntimeException("Unable to query cloud search results: " + response.getMessage()); } catch( IOException io ) { throw Throwables.propagate(io); } }
@Override public String importControl(byte[] zipFileData) throws IOException { StagingFile staging = stagingService.createStagingArea(); try { fileSystemService.unzipFile(staging, new ByteArrayInputStream(zipFileData), ArchiveType.ZIP); Reader reader = new InputStreamReader(fileSystemService.read(staging, CONTROL_XML)); StringWriter writer = new StringWriter(); CharStreams.copy(reader, writer); return writer.toString(); } catch( IOException io ) { Throwables.propagate(io); return null; // unreachable } finally { stagingService.removeStagingArea(staging, true); } }
/** * Retrieves the description from an IMS manifest. */ public static String getDescriptionFromManifest(Reader xml) throws XmlPullParserException, IOException { StringWriter sr = new StringWriter(); CharStreams.copy(xml, sr); String bufXml = sr.getBuffer().toString(); String v = getValueForPath("manifest/metadata/lom/general/description/string|langstring", new StringReader( bufXml)); if( v == null ) { v = getValueForPath( "manifest/organizations/organization/item/metadata/lom/general/description/string|langstring", new StringReader(bufXml)); } return v; }
@SuppressWarnings("nls") public void registerPlugins() throws IOException, JpfException { List<TLEPluginLocation> locations = new ArrayList<TLEPluginLocation>(); List<PluginDetails> allPluginDetails = downloadService.getAllPluginDetails("admin-console"); for( PluginDetails details : allPluginDetails ) { File file = File.createTempFile("manifest", ".xml"); try( OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8") ) { CharStreams.copy(new StringReader(details.getManifestXml()), writer); } finally { file.deleteOnExit(); } URL manifestUrl = file.toURI().toURL(); ManifestInfo info = pluginManager.getRegistry().readManifestInfo(manifestUrl); TLEPluginLocation location = new TLEPluginLocation(info, null, details.getBaseUrl(), manifestUrl); locations.add(location); } pluginManager.publishPlugins(locations.toArray(new TLEPluginLocation[locations.size()])); }
private ObjectNode createItemFromFile(String jsonFile, String token, String stagingUuid, int responseCode, boolean returnError) throws Exception { final StringWriter sw = new StringWriter(); final InputStream input = ItemApiEditTest.class.getResourceAsStream(jsonFile); try { CharStreams.copy(new InputStreamReader(input), sw); } finally { Closeables.close(input, true); } String newItemJson = sw.toString(); return createItemFromString(newItemJson, token, stagingUuid, responseCode, returnError); }
private void assertFileInCache (File file,String key) throws IOException { InputStream in = new FileInputStream(file); try { Reader reader = new InputStreamReader(in); String text = CharStreams.toString(reader); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(text); JsonObject jsonCache = je.getAsJsonObject(); JsonElement elt = jsonCache.get(key); JsonObject generatedObj = elt.getAsJsonObject(); boolean generated = generatedObj.get("generated").getAsBoolean(); assertTrue("Test not generated", generated); } finally { if (in!=null) in.close(); } }
private long readModifedTimeInCacheForFile (File file,String key) throws IOException { InputStream in = new FileInputStream(file); try { Reader reader = new InputStreamReader(in); String text = CharStreams.toString(reader); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(text); JsonObject jsonCache = je.getAsJsonObject(); JsonElement elt = jsonCache.get(key); JsonObject generatedObj = elt.getAsJsonObject(); long modified = generatedObj.get("modified").getAsLong(); return modified; } finally { if (in!=null) in.close(); } }
@Override public String post(final HttpServletRequest req, final HttpServletResponse res) { final String result = ""; try { final String body = CharStreams.toString(req.getReader()); final DefaultJsonMapper mapper = new DefaultJsonMapper(); final WebhookObject webhookObject = mapper.toJavaObject(body, WebhookObject.class); final Map<String, String[]> params = req.getParameterMap(); for (final WebhookEntry webhookEntry : webhookObject.getEntryList()) { handleWebhookEntry(webhookEntry, params); } } catch (final Exception e) { handleException(e); } return result; }
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL resource = classLoader.getResource(indexPagePath); URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{resource}); InputStream input = urlClassLoader.getResourceAsStream(indexPagePath); String result = CharStreams.toString(new InputStreamReader(input, Charsets.UTF_8)); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(result); } catch (Exception e) { response.getWriter().print(e); LOG.error("error : ", e); } }
private CompilationUnit get(Class<?> c) throws IOException { URL u = getSourceURL(c); try (Reader reader = Resources.asCharSource(u, UTF_8).openStream()) { String body = CharStreams.toString(reader); // TODO: Hack to remove annotations so Janino doesn't choke. Need to reconsider this problem... body = body.replaceAll("@\\w+(?:\\([^\\\\]*?\\))?", ""); for(Replacement r : REPLACERS){ body = r.apply(body); } // System.out.println("original"); // System.out.println(body);; // System.out.println("decompiled"); // System.out.println(decompile(c)); try { return new Parser(new Scanner(null, new StringReader(body))).parseCompilationUnit(); } catch (CompileException e) { logger.warn("Failure while parsing function class:\n{}", body, e); return null; } } }
@SuppressWarnings("unchecked") private List<Map<String, Object>> loadSpecs() { String pathToResource = "syncPointSpec.json"; InputStream stream = getClass().getClassLoader().getResourceAsStream(pathToResource); if (stream == null) { throw new RuntimeException("Failed to find syncPointSpec.json resource."); } try (InputStreamReader reader = new InputStreamReader(stream)) { return (List) JsonMapper.parseJsonValue(CharStreams.toString(reader)); } catch (IOException e) { throw new RuntimeException(e); } }
@Test public void testCloudStorageSignUrl() throws IOException { StorageClient storage = StorageClient.getInstance(IntegrationTestUtils.ensureDefaultApp()); Bucket bucket = storage.bucket(); Blob blob = createTextBlob(bucket, "Signed URL Test"); URL url = blob.signUrl(3600, TimeUnit.SECONDS); try (InputStream in = url.openStream()) { String result = CharStreams.toString(new InputStreamReader(in)); assertEquals("Signed URL Test", result); } finally { blob.delete(); } }
public static synchronized String getApiKey() { if (apiKey == null) { try (InputStream stream = new FileInputStream(IT_API_KEY_PATH)) { apiKey = CharStreams.toString(new InputStreamReader(stream)).trim(); } catch (IOException e) { String msg = String.format("Failed to read API key from %s. " + "Integration tests require an API key obtained from a Firebase " + "project. See CONTRIBUTING.md for more details.", IT_API_KEY_PATH); throw new RuntimeException(msg, e); } } return apiKey; }
private static UserException.Builder addResponseInfo(UserException.Builder builder, Response response) { if(response == null){ return builder; } try { builder.addContext("Response Status", response.getStatusInfo().getStatusCode()); builder.addContext("Response Reason", response.getStatusInfo().getReasonPhrase()); String string = CharStreams.toString(new InputStreamReader((InputStream) response.getEntity())); builder.addContext("Response Body", string); } catch(Exception ex){ logger.warn("Failure while decoding exception", ex); } return builder; }
private void readExistingEntriesInto(Collection<String> services) { try { FileObject existing = getFiler().getResource(StandardLocation.CLASS_OUTPUT, key.packageName, key.relativeName); FluentIterable.from(CharStreams.readLines(existing.openReader(true))) .filter(Predicates.not(Predicates.contains(SERVICE_FILE_COMMENT_LINE))) .copyInto(services); } catch (Exception ex) { // unable to read existing file } }
public static String readResource(String resourceFile) { try (InputStreamReader reader = new InputStreamReader(GetViewRequestExecutor.class.getResourceAsStream(resourceFile), StandardCharsets.UTF_8)) { return CharStreams.toString(reader); } catch (IOException e) { throw new RuntimeException("Could not find resource " + resourceFile, e); } }
/** * @param resourceName * the classpath-relative location of the to-be-read resource */ private static List<String> getFileLines(final String resourceName) throws IOException { InputSupplier<InputStreamReader> readerSupplier = CharStreams.newReaderSupplier( new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName); } }, Charsets.UTF_8); return CharStreams.readLines(readerSupplier); }
/***/ public static String getContentsFromFileEntry(final ZipEntry entry, String rootName) throws IOException, URISyntaxException { URL rootURL = Thread.currentThread().getContextClassLoader().getResource(rootName); try (final ZipFile root = new ZipFile(new File(rootURL.toURI()));) { InputSupplier<InputStreamReader> readerSupplier = CharStreams.newReaderSupplier( new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return root.getInputStream(entry); } }, Charsets.UTF_8); return CharStreams.toString(readerSupplier); } }
private void createArchive(URI baseDir) throws IOException { File directory = new File(java.net.URI.create(baseDir.toString())); File lib = new File(directory, "lib"); assertTrue(lib.mkdir()); File nfar = new File(lib, host.archiveProjectId + ".nfar"); final ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(nfar)); zipOutputStream.putNextEntry(new ZipEntry("src/A.js")); zipOutputStream.putNextEntry(new ZipEntry("src/B.js")); zipOutputStream.putNextEntry(new ZipEntry("src/sub/B.js")); zipOutputStream.putNextEntry(new ZipEntry("src/sub/C.js")); zipOutputStream.putNextEntry(new ZipEntry("src/sub/leaf/D.js")); zipOutputStream.putNextEntry(new ZipEntry(IN4JSProject.N4MF_MANIFEST)); // this will close the stream CharStreams.write("ProjectId: " + host.archiveProjectId + "\n" + "ProjectType: library\n" + "ProjectVersion: 0.0.1-SNAPSHOT\n" + "VendorId: org.eclipse.n4js\n" + "VendorName: \"Eclipse N4JS Project\"\n" + "Output: \"src-gen\"\n" + "Sources {\n" + " source {" + " \"src\"\n" + " }\n" + "}", CharStreams.newWriterSupplier(new OutputSupplier<ZipOutputStream>() { @Override public ZipOutputStream getOutput() throws IOException { return zipOutputStream; } }, Charsets.UTF_8)); host.setArchiveFileURI(URI.createURI(nfar.toURI().toString())); }
private void createArchive(String projectName) throws CoreException, IOException { IProject project = workspace.getProject(projectName); IFolder libFolder = project.getFolder(LIB_FOLDER_NAME); libFolder.create(false, true, null); IFile archiveFile = libFolder.getFile(host.archiveProjectId + ".nfar"); ByteArrayOutputStream byteArrayOutputSteam = new ByteArrayOutputStream(); final ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputSteam); zipOutputStream.putNextEntry(new ZipEntry("src/A.js")); zipOutputStream.putNextEntry(new ZipEntry("src/B.js")); zipOutputStream.putNextEntry(new ZipEntry("src/sub/B.js")); zipOutputStream.putNextEntry(new ZipEntry("src/sub/C.js")); zipOutputStream.putNextEntry(new ZipEntry("src/sub/leaf/D.js")); zipOutputStream.putNextEntry(new ZipEntry(IN4JSProject.N4MF_MANIFEST)); // this will close the stream CharStreams.write("ProjectId: " + host.archiveProjectId + "\n" + "ProjectType: library\n" + "ProjectVersion: 0.0.1-SNAPSHOT\n" + "VendorId: org.eclipse.n4js\n" + "VendorName: \"Eclipse N4JS Project\"\n" + "Libraries { \"" + LIB_FOLDER_NAME + "\"\n }\n" + "Output: \"src-gen\"" + "Sources {\n" + " source { " + " \"src\"\n" + " }\n" + "}\n", CharStreams.newWriterSupplier(new OutputSupplier<ZipOutputStream>() { @Override public ZipOutputStream getOutput() throws IOException { return zipOutputStream; } }, Charsets.UTF_8)); archiveFile.create(new ByteArrayInputStream(byteArrayOutputSteam.toByteArray()), false, null); host.setArchiveFileURI(URI.createPlatformResourceURI(archiveFile.getFullPath().toString(), true)); }
@Override public ModificationScript build() { // check parameters if (name == null) { throw new AfsException("Name is not set"); } if (type == null) { throw new AfsException("Script type is not set"); } if (content == null) { throw new AfsException("Content is not set"); } if (context.getStorage().getChildNode(context.getFolderInfo().getId(), name).isPresent()) { throw new AfsException("Parent folder already contains a '" + name + "' node"); } // create project file NodeInfo info = context.getStorage().createNode(context.getFolderInfo().getId(), name, ModificationScript.PSEUDO_CLASS, "", ModificationScript.VERSION, new NodeGenericMetadata().setString(ModificationScript.SCRIPT_TYPE, type.name())); // store script try (Reader reader = new StringReader(content); Writer writer = new OutputStreamWriter(context.getStorage().writeBinaryData(info.getId(), ModificationScript.SCRIPT_CONTENT), StandardCharsets.UTF_8)) { CharStreams.copy(reader, writer); } catch (IOException e) { throw new UncheckedIOException(e); } context.getStorage().flush(); return new ModificationScript(new ProjectFileCreationContext(info, context.getStorage(), context.getFileSystem())); }
@Override public String readScript() { try { return CharStreams.toString(new InputStreamReader(storage.readBinaryData(info.getId(), SCRIPT_CONTENT).orElseThrow(AssertionError::new), StandardCharsets.UTF_8)); } catch (IOException e) { throw new UncheckedIOException(e); } }
@Override public void writeScript(String content) { try (Reader reader = new StringReader(content); Writer writer = new OutputStreamWriter(storage.writeBinaryData(info.getId(), SCRIPT_CONTENT), StandardCharsets.UTF_8)) { CharStreams.copy(reader, writer); } catch (IOException e) { throw new UncheckedIOException(e); } storage.updateModificationTime(info.getId()); storage.flush(); notifyDependencyListeners(); }
@Override public void process(Network network, ComputationManager computationManager) throws Exception { if (Files.exists(script)) { LOGGER.debug("Execute JS post processor {}", script); try (Reader reader = Files.newBufferedReader(script)) { Networks.runScript(network, reader, printToStdOut ? null : CharStreams.nullWriter()); } } }
@Override public void run() { try { result = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8)); stream.close(); } catch (IOException e) { result = "Failed reading result for stream " + stream; } }
@Override protected IStatus run(IProgressMonitor monitor) { BuildConfiguration buildConfig = CorePlugin.configurationManager() .loadBuildConfiguration(new File(project.getRawLocationURI())); RunConfiguration runConfiguration = CorePlugin.configurationManager().createDefaultRunConfiguration(buildConfig); BuildLauncher launcher = CorePlugin.gradleWorkspaceManager().getGradleBuild(buildConfig) .newBuildLauncher(runConfiguration, CharStreams.nullWriter(), getTransientRequestAttributes(GradleConnector.newCancellationTokenSource().token(), monitor)); launcher.forTasks(":" + project.getName() + ":gfBundle").run(); return Status.OK_STATUS; }