List of usage examples for com.google.common.io Resources toString
public static String toString(URL url, Charset charset) throws IOException
From source file:com.mgmtp.perfload.perfalyzer.reporting.ReportCreator.java
public void createReport(final List<PerfAlyzerFile> files) throws IOException { Function<PerfAlyzerFile, String> classifier = perfAlyzerFile -> { String marker = perfAlyzerFile.getMarker(); return marker == null ? "Overall" : marker; };// w w w. j av a 2s . co m Supplier<Map<String, List<PerfAlyzerFile>>> mapFactory = () -> new TreeMap<>(Ordering.explicit(tabNames)); Map<String, List<PerfAlyzerFile>> filesByMarker = files.stream() .collect(Collectors.groupingBy(classifier, mapFactory, toList())); Map<String, SortedSetMultimap<String, PerfAlyzerFile>> contentItemFiles = new LinkedHashMap<>(); for (Entry<String, List<PerfAlyzerFile>> entry : filesByMarker.entrySet()) { SortedSetMultimap<String, PerfAlyzerFile> contentItemFilesByMarker = contentItemFiles.computeIfAbsent( entry.getKey(), s -> TreeMultimap.create(new ItemComparator(reportContentsConfigMap.get("priorities")), Ordering.natural())); for (PerfAlyzerFile perfAlyzerFile : entry.getValue()) { File file = perfAlyzerFile.getFile(); String groupKey = removeExtension(file.getPath()); boolean excluded = false; for (Pattern pattern : reportContentsConfigMap.get("exclusions")) { Matcher matcher = pattern.matcher(groupKey); if (matcher.matches()) { excluded = true; log.debug("Excluded from report: {}", groupKey); break; } } if (!excluded) { contentItemFilesByMarker.put(groupKey, perfAlyzerFile); } } } // explicitly copy it because it is otherwise filtered from the report in order to only show in the overview String loadProfilePlot = new File("console", "[loadprofile].png").getPath(); copyFile(new File(soureDir, loadProfilePlot), new File(destDir, loadProfilePlot)); Map<String, List<ContentItem>> tabItems = new LinkedHashMap<>(); Map<String, QuickJump> quickJumps = new HashMap<>(); Set<String> tabNames = contentItemFiles.keySet(); for (Entry<String, SortedSetMultimap<String, PerfAlyzerFile>> tabEntry : contentItemFiles.entrySet()) { String tab = tabEntry.getKey(); SortedSetMultimap<String, PerfAlyzerFile> filesForTab = tabEntry.getValue(); List<ContentItem> contentItems = tabItems.computeIfAbsent(tab, list -> new ArrayList<>()); Map<String, String> quickJumpMap = new LinkedHashMap<>(); quickJumps.put(tab, new QuickJump(tab, quickJumpMap)); int itemIndex = 0; for (Entry<String, Collection<PerfAlyzerFile>> itemEntry : filesForTab.asMap().entrySet()) { String title = itemEntry.getKey(); Collection<PerfAlyzerFile> itemFiles = itemEntry.getValue(); TableData tableData = null; String plotSrc = null; for (PerfAlyzerFile file : itemFiles) { if ("png".equals(getExtension(file.getFile().getName()))) { plotSrc = file.getFile().getPath(); copyFile(new File(soureDir, plotSrc), new File(destDir, plotSrc)); } else { tableData = createTableData(file.getFile()); } } // strip off potential marker title = substringBefore(title, "{"); String[] titleParts = split(title, SystemUtils.FILE_SEPARATOR); StringBuilder sb = new StringBuilder(50); String separator = " - "; sb.append(resourceBundle.getString(titleParts[0])); sb.append(separator); sb.append(resourceBundle.getString(titleParts[1])); List<String> fileNameParts = extractFileNameParts(titleParts[1], true); if (titleParts[1].contains("[distribution]")) { String operation = fileNameParts.get(1); sb.append(separator); sb.append(operation); } else if ("comparison".equals(titleParts[0])) { String operation = fileNameParts.get(1); sb.append(separator); sb.append(operation); } else if (titleParts[1].contains("[gclog]")) { if (fileNameParts.size() > 1) { sb.append(separator); sb.append(fileNameParts.get(1)); } } title = sb.toString(); ContentItem item = new ContentItem(tab, itemIndex, title, tableData, plotSrc, resourceBundle.getString("report.topLink")); contentItems.add(item); quickJumpMap.put(tab + "_" + itemIndex, title); itemIndex++; } } NavBar navBar = new NavBar(tabNames, quickJumps); String testName = removeExtension(testMetadata.getTestPlanFile()); OverviewItem overviewItem = new OverviewItem(testMetadata, resourceBundle, locale); Content content = new Content(tabItems); String perfAlyzerVersion; try { perfAlyzerVersion = Resources.toString(Resources.getResource("perfAlyzer.version"), Charsets.UTF_8); } catch (IOException ex) { log.error("Could not read perfAlyzer version from classpath resource 'perfAlyzer.version'", ex); perfAlyzerVersion = ""; } String dateTimeString = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withLocale(locale) .format(ZonedDateTime.now()); String createdString = String.format(resourceBundle.getString("footer.created"), perfAlyzerVersion, dateTimeString); HtmlSkeleton html = new HtmlSkeleton(testName, createdString, navBar, overviewItem, content); writeReport(html); }
From source file:org.apache.hive.ptest.Phase.java
protected static String readResource(String resource) throws IOException { return Resources.toString(Resources.getResource(resource), Charsets.UTF_8); }
From source file:org.apache.druid.emitter.graphite.WhiteListBasedConverter.java
private ImmutableSortedMap<String, ImmutableSet<String>> readMap(final String mapPath) { String fileContent;/* w w w.j a v a 2 s. co m*/ String actualPath = mapPath; try { if (Strings.isNullOrEmpty(mapPath)) { URL resource = this.getClass().getClassLoader().getResource("defaultWhiteListMap.json"); actualPath = resource.getFile(); LOGGER.info("using default whiteList map located at [%s]", actualPath); fileContent = Resources.toString(resource, Charset.defaultCharset()); } else { fileContent = Files.asCharSource(new File(mapPath), Charset.forName("UTF-8")).read(); } return mapper.reader(new TypeReference<ImmutableSortedMap<String, ImmutableSet<String>>>() { }).readValue(fileContent); } catch (IOException e) { throw new ISE(e, "Got an exception while parsing file [%s]", actualPath); } }
From source file:org.mayocat.shop.front.views.WebViewMessageBodyWriter.java
private void writeDeveloperError(WebView webView, Exception e, OutputStream entityStream) { try {//from ww w .j a v a 2 s.co m // Note: // This could be seen as a "server error", but we don't set the Status header to 500 because we want to be // able to distinguish between actual server errors (internal Mayocat Shop server error) and theme // developers errors (which this is). // This is comes at play when setting up monitoring with alerts on a number of 5xx response above a // certain threshold. // Re-serialize the context as json with indentation for better debugging ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.INDENT_OUTPUT, true); Map<String, Object> context = webView.data(); String jsonContext = mapper.writeValueAsString(context); Template error = new Template("developerError", Resources.toString(Resources.getResource("templates/developerError.html"), Charsets.UTF_8)); Map<String, Object> errorContext = Maps.newHashMap(); errorContext.put("error", StringEscapeUtils.escapeXml(cleanErrorMessageForDisplay(e.getMessage()))); errorContext.put("stackTrace", StringEscapeUtils.escapeXml(ExceptionUtils.getStackTrace(e))); errorContext.put("context", StringEscapeUtils.escapeXml(jsonContext).trim()); errorContext.put("rawContext", jsonContext); errorContext.put("template", webView.template().toString()); engine.get().register(error); String rendered = engine.get().render(error.getId(), mapper.writeValueAsString(errorContext)); entityStream.write(rendered.getBytes()); } catch (Exception e1) { throw new RuntimeException(e1); } }
From source file:io.flutter.preview.RenderHelper.java
private void render(@NotNull RenderRequest request) { final FlutterOutline widget = request.widget; try {/*www .j a v a2 s . com*/ final String packagePath = request.pubRoot.getPath(); final File dartToolDirectory = new File(packagePath, ".dart_tool"); final File flutterDirectory = new File(dartToolDirectory, "flutter"); final File designerDirectory = new File(flutterDirectory, "designer"); final File toRenderFile = new File(designerDirectory, "to_render.dart"); FileUtil.writeToFile(toRenderFile, request.codeToRender); final String widgetCreation = "new " + request.widgetClass + "." + request.widgetConstructor + "();"; final URL templateUri = RenderHelper.class.getResource("render_server_template.txt"); String template = Resources.toString(templateUri, StandardCharsets.UTF_8); template = template.replace("// TEMPLATE_VALUE: import library to render", "import '" + toRenderFile.getName() + "';"); template = template.replace("new Container(); // TEMPLATE_VALUE: create widget", widgetCreation); template = template.replace("{}; // TEMPLATE_VALUE: use flutterDesignerWidgets", "flutterDesignerWidgets;"); template = template.replace("350.0 /*TEMPLATE_VALUE: width*/", request.width + ".0"); template = template.replace("400.0 /*TEMPLATE_VALUE: height*/", request.height + ".0"); final File renderServerFile = new File(designerDirectory, "render_server.dart"); final String renderServerPath = renderServerFile.getPath(); FileUtil.writeToFile(renderServerFile, template); // If the process is dead, clear the instance. if (myApp != null && !myApp.isConnected()) { myProcessRequest = null; myApp = null; } // Check if the current render server process is compatible with the new request. // If it is, attempt to perform hot reload. // If not successful, terminate the process. boolean canRenderWithCurrentProcess = false; if (myProcessRequest != null && myApp != null) { if (Objects.equals(myProcessRequest.pubRoot.getPath(), packagePath)) { try { final DaemonApi.RestartResult restartResult = myApp.performHotReload(false).get(5000, TimeUnit.MILLISECONDS); if (restartResult.ok()) { canRenderWithCurrentProcess = true; } } catch (Throwable ignored) { } } if (!canRenderWithCurrentProcess) { terminateCurrentProcess("Project root or file changed, or reload failed"); } } // If there is no rendering server process, start a new one. // Wait for it to start. if (myApp == null) { final FlutterCommand command = request.flutterSdk.flutterRunOnTester(request.pubRoot, renderServerPath); final GeneralCommandLine commandLine = command.createGeneralCommandLine(request.project); // Windows is not a supported Flutter target platform. // Set FLUTTER_TEST to force using Android (everywhere, not just on Windows) commandLine.getEnvironment().put("FLUTTER_TEST", "true"); final FlutterApp app = FlutterApp.start(new ExecutionEnvironment(), request.project, request.module, RunMode.DEBUG, FlutterDevice.getTester(), commandLine, null, null); final CountDownLatch startedLatch = new CountDownLatch(1); app.addStateListener(new FlutterApp.FlutterAppListener() { @Override public void stateChanged(FlutterApp.State newState) { if (newState == FlutterApp.State.STARTED) { startedLatch.countDown(); } if (newState == FlutterApp.State.TERMINATING) { myProcessRequest = null; myApp = null; } } }); final boolean started = Uninterruptibles.awaitUninterruptibly(startedLatch, 10000, TimeUnit.MILLISECONDS); if (!started) { terminateCurrentProcess("Initial start timeout."); invokeIfSameRequest(request, () -> request.listener.onFailure(RenderProblemKind.TIMEOUT_START, request.widget)); return; } myProcessRequest = request; myApp = app; } // Ask to render the widget. final CountDownLatch responseReceivedLatch = new CountDownLatch(1); final AtomicReference<JsonObject> responseRef = new AtomicReference<>(); myApp.callServiceExtension("ext.flutter.designer.render").thenAccept((response) -> { responseRef.set(response); responseReceivedLatch.countDown(); }); // Wait for the response. final boolean responseReceived = Uninterruptibles.awaitUninterruptibly(responseReceivedLatch, 4000, TimeUnit.MILLISECONDS); if (!responseReceived) { terminateCurrentProcess("Render response timeout."); invokeIfSameRequest(request, () -> request.listener.onFailure(RenderProblemKind.TIMEOUT_RENDER, widget)); return; } final JsonObject response = responseRef.get(); if (response.has("exception")) { invokeIfSameRequest(request, () -> request.listener.onRemoteException(widget, response)); return; } // Send the respose to the client. invokeIfSameRequest(request, () -> request.listener.onResponse(widget, response)); } catch (Throwable e) { terminateCurrentProcess("Exception"); invokeIfSameRequest(request, () -> request.listener.onLocalException(widget, e)); } }
From source file:org.openscada.vi.ui.draw2d.SymbolController.java
private void loadScript(final String module) throws Exception { this.logStream.println(String.format("Loading script module: %s", module)); final String moduleSource = Resources.toString(new URL(module), Charset.forName("UTF-8")); new ScriptExecutor(this.engine, moduleSource, this.classLoader).execute(this.scriptContext); }
From source file:mimeparser.MimeMessageConverter.java
/** * Convert an EML file to PDF.//from w w w .jav a 2s .c o m * @throws Exception */ public static void convertToPdf(String emlPath, String pdfOutputPath, boolean outputHTML, boolean hideHeaders, boolean extractAttachments, String attachmentsdir, List<String> extParams) throws Exception { Logger.info("Start converting %s to %s", emlPath, pdfOutputPath); Logger.debug("Read eml file from %s", emlPath); final MimeMessage message = new MimeMessage(null, new FileInputStream(emlPath)); /* ######### Parse Header Fields ######### */ Logger.debug("Read and decode header fields"); String subject = message.getSubject(); String from = message.getHeader("From", null); if (from == null) { from = message.getHeader("Sender", null); } try { from = MimeUtility.decodeText(MimeUtility.unfold(from)); } catch (Exception e) { // ignore this error } String[] recipients = new String[0]; String recipientsRaw = message.getHeader("To", null); if (!Strings.isNullOrEmpty(recipientsRaw)) { try { recipientsRaw = MimeUtility.unfold(recipientsRaw); recipients = recipientsRaw.split(","); for (int i = 0; i < recipients.length; i++) { recipients[i] = MimeUtility.decodeText(recipients[i]); } } catch (Exception e) { // ignore this error } } String sentDateStr = message.getHeader("date", null); /* ######### Parse the mime structure ######### */ Logger.info("Mime Structure of %s:\n%s", emlPath, MimeMessageParser.printStructure(message)); Logger.debug("Find the main message body"); MimeObjectEntry<String> bodyEntry = MimeMessageParser.findBodyPart(message); String charsetName = bodyEntry.getContentType().getParameter("charset"); Logger.info("Extract the inline images"); final HashMap<String, MimeObjectEntry<String>> inlineImageMap = MimeMessageParser .getInlineImageMap(message); /* ######### Embed images in the html ######### */ String htmlBody = bodyEntry.getEntry(); if (bodyEntry.getContentType().match("text/html")) { htmlBody = String.format(HTML_CHARSET_TEMPLATE, charsetName, htmlBody.replaceAll("(?i)</?(html|body)>", "")); if (inlineImageMap.size() > 0) { Logger.debug("Embed the referenced images (cid) using <img src=\"data:image ...> syntax"); // find embedded images and embed them in html using <img src="data:image ...> syntax htmlBody = StringReplacer.replace(htmlBody, IMG_CID_REGEX, new StringReplacerCallback() { @Override public String replace(Matcher m) throws Exception { MimeObjectEntry<String> base64Entry = inlineImageMap.get("<" + m.group(1) + ">"); // found no image for this cid, just return the matches string as it is if (base64Entry == null) { return m.group(); } return "data:" + base64Entry.getContentType().getBaseType() + ";base64," + base64Entry.getEntry() + "\""; } }); } } else { Logger.debug( "No html message body could be found, fall back to text/plain and embed it into a html document"); // replace \n line breaks with <br> htmlBody = htmlBody.replace("\n", "<br>").replace("\r", ""); // replace whitespace with htmlBody = htmlBody.replace(" ", " "); htmlBody = String.format(HTML_WRAPPER_TEMPLATE, charsetName, htmlBody); if (inlineImageMap.size() > 0) { Logger.debug("Embed the referenced images (cid) using <img src=\"data:image ...> syntax"); // find embedded images and embed them in html using <img src="data:image ...> syntax htmlBody = StringReplacer.replace(htmlBody, IMG_CID_PLAIN_REGEX, new StringReplacerCallback() { @Override public String replace(Matcher m) throws Exception { MimeObjectEntry<String> base64Entry = inlineImageMap.get("<" + m.group(1) + ">"); // found no image for this cid, just return the matches string if (base64Entry == null) { return m.group(); } return "<img src=\"data:" + base64Entry.getContentType().getBaseType() + ";base64," + base64Entry.getEntry() + "\" />"; } }); } } Logger.debug("Successfully parsed the .eml and converted it into html:"); Logger.debug("---------------Result-------------"); Logger.debug("Subject: %s", subject); Logger.debug("From: %s", from); if (recipients.length > 0) { Logger.debug("To: %s", Joiner.on(", ").join(recipients)); } Logger.debug("Date: %s", sentDateStr); String bodyExcerpt = htmlBody.replace("\n", "").replace("\r", ""); if (bodyExcerpt.length() >= 60) { bodyExcerpt = bodyExcerpt.substring(0, 40) + " [...] " + bodyExcerpt.substring(bodyExcerpt.length() - 20, bodyExcerpt.length()); } Logger.debug("Body (excerpt): %s", bodyExcerpt); Logger.debug("----------------------------------"); Logger.info("Start conversion to " + (outputHTML ? "html" : "pdf")); File pdf = new File(pdfOutputPath); File tmpHtmlHeader = null; if (!hideHeaders) { String headers = ""; if (!Strings.isNullOrEmpty(from)) { headers += String.format(HEADER_FIELD_TEMPLATE, "From", HtmlEscapers.htmlEscaper().escape(from)); } if (!Strings.isNullOrEmpty(subject)) { headers += String.format(HEADER_FIELD_TEMPLATE, "Subject", "<b>" + HtmlEscapers.htmlEscaper().escape(subject) + "<b>"); } if (recipients.length > 0) { headers += String.format(HEADER_FIELD_TEMPLATE, "To", HtmlEscapers.htmlEscaper().escape(Joiner.on(", ").join(recipients))); } if (!Strings.isNullOrEmpty(sentDateStr)) { headers += String.format(HEADER_FIELD_TEMPLATE, "Date", HtmlEscapers.htmlEscaper().escape(sentDateStr)); } if (outputHTML) htmlBody = htmlBody.replace("</head><body>", "<style>.header-name {color:#9E9E9E; text-align:right;}</style></head><body><table style='border:1px solid #DDD; margin: 8px'>" + headers + "</table>"); else { tmpHtmlHeader = new File(pdf.getParentFile(), Files.getNameWithoutExtension(pdfOutputPath) + "_h.html"); String tmpHtmlHeaderStr = Resources.toString(Resources.getResource("header.html"), StandardCharsets.UTF_8); Files.write(String.format(tmpHtmlHeaderStr, headers), tmpHtmlHeader, StandardCharsets.UTF_8); // Append this script tag dirty to the bottom htmlBody += String.format(ADD_HEADER_IFRAME_JS_TAG_TEMPLATE, tmpHtmlHeader.toURI(), Resources.toString(Resources.getResource("contentScript.js"), StandardCharsets.UTF_8)); } } File tmpHtml = new File(pdf.getParentFile(), Files.getNameWithoutExtension(pdfOutputPath) + ".html"); Logger.debug("Write html to file %s", tmpHtml.getAbsolutePath()); Files.write(htmlBody, tmpHtml, Charset.forName(charsetName)); if (!outputHTML) { Logger.debug("Write pdf to %s", pdf.getAbsolutePath()); List<String> cmd = new ArrayList<String>(Arrays.asList("wkhtmltopdf", "--viewport-size", "2480x3508", // "--disable-smart-shrinking", "--image-quality", "100", "--encoding", charsetName)); cmd.addAll(extParams); cmd.add(tmpHtml.getAbsolutePath()); cmd.add(pdf.getAbsolutePath()); Logger.debug("Execute: %s", Joiner.on(' ').join(cmd)); execCommand(cmd); if (!tmpHtml.delete()) { tmpHtml.deleteOnExit(); } if (tmpHtmlHeader != null) { if (!tmpHtmlHeader.delete()) { tmpHtmlHeader.deleteOnExit(); } } } /* ######### Save attachments ######### */ if (extractAttachments) { Logger.debug("Start extracting attachments"); File attachmentDir = null; if (!Strings.isNullOrEmpty(attachmentsdir)) { attachmentDir = new File(attachmentsdir); } else { attachmentDir = new File(pdf.getParentFile(), Files.getNameWithoutExtension(pdfOutputPath) + "-attachments"); } attachmentDir.mkdirs(); Logger.info("Extract attachments to %s", attachmentDir.getAbsolutePath()); List<Part> attachmentParts = MimeMessageParser.getAttachments(message); Logger.debug("Found %s attachments", attachmentParts.size()); for (int i = 0; i < attachmentParts.size(); i++) { Logger.debug("Process Attachment %s", i); Part part = attachmentParts.get(i); String attachmentFilename = null; try { attachmentFilename = part.getFileName(); } catch (Exception e) { // ignore this error } File attachFile = null; if (!Strings.isNullOrEmpty(attachmentFilename)) { attachFile = new File(attachmentDir, attachmentFilename); } else { String extension = ""; // try to find at least the file extension via the mime type try { extension = MimeTypes.getDefaultMimeTypes().forName(part.getContentType()).getExtension(); } catch (Exception e) { // ignore this error } Logger.debug("Attachment %s did not hold any name, use random name", i); attachFile = File.createTempFile("nameless-", extension, attachmentDir); } Logger.debug("Save Attachment %s to %s", i, attachFile.getAbsolutePath()); FileOutputStream fos = new FileOutputStream(attachFile); ByteStreams.copy(part.getInputStream(), fos); fos.close(); } } Logger.info("Conversion finished"); }
From source file:com.facebook.buck.go.GoDescriptors.java
private static String extractTestMainGenerator() { try {/*from w w w.j a va 2s . c o m*/ return Resources.toString(Resources.getResource(TEST_MAIN_GEN_PATH), Charsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:li.klass.fhem.service.graph.gplot.GPlotParser.java
private Map<String, GPlotDefinition> readDefinitionsFromJar(URL url) throws IOException, URISyntaxException { Map<String, GPlotDefinition> result = newHashMap(); JarURLConnection con = (JarURLConnection) url.openConnection(); JarFile archive = con.getJarFile(); Enumeration<JarEntry> entries = archive.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().endsWith(".gplot")) { String filename = entry.getName().substring(entry.getName().lastIndexOf("/") + 1); String plotName = filename.substring(0, filename.indexOf(".")); URL resource = GPlotParser.class.getResource(filename); result.put(plotName, parse(Resources.toString(resource, Charsets.UTF_8))); }//from w ww . j a va 2 s.c o m } return result; }
From source file:de.scoopgmbh.copper.monitoring.client.doc.DocGeneratorMain.java
public File writeSummary(List<IntegrationtestBase> tests) { File newTextFile = new File(new File(System.getProperty("concordion.output.dir")).getAbsolutePath() + "/de/scoopgmbh/copper/monitoring/client/doc/index.html"); URL url = Resources.getResource("de/scoopgmbh/copper/monitoring/client/doc/index.html"); String file;// w w w . ja v a2 s .c o m try { file = Resources.toString(url, Charsets.UTF_8); } catch (IOException e1) { throw new RuntimeException(e1); } StringBuilder list = new StringBuilder(); list.append("<ul>"); for (IntegrationtestBase test : tests) { String relative = getRelativePath(newTextFile, new File(getGeneratedHtmlPath(test))); list.append("<li>"); list.append("<a href=\""); list.append(relative); list.append("\"> "); list.append(test.getTitle()); list.append("</a>"); list.append("</li>"); } list.append("</ul>"); file = file.replace("<!-- $testlist -->", list.toString()); try { FileWriter fw = new FileWriter(newTextFile); fw.write(file); fw.close(); } catch (IOException e) { throw new RuntimeException(e); } return newTextFile; }