List of usage examples for java.io Writer close
public abstract void close() throws IOException;
From source file:experiment.ExperimentLogger.java
private void flushtoTempFile() throws FileNotFoundException, IOException { String ret = System.getProperty("line.separator"); //for (Integer c : stateCount) // content.append(c.toString()+ret); Writer output = new BufferedWriter(new FileWriter(configFile)); try {//from w ww .java 2 s . co m //FileWriter always assumes default encoding is OK! output.write(content.toString()); } finally { output.close(); } }
From source file:com.soulgalore.crawler.run.CrawlAndVerifyAssetsToCsv.java
private void crawl() { final Injector injector = Guice.createInjector(new CrawlModule()); final Crawler crawler = injector.getInstance(Crawler.class); final StringBuilder builder = new StringBuilder(); builder.append("URL,parent,error\n"); final CrawlerResult result = crawler.getUrls(getConfiguration()); System.out.println("Crawled " + result.getVerifiedURLResponses().size() + " pages"); System.out.println("Start verify assets ..."); AssetsVerifier verifier = injector.getInstance(AssetsVerifier.class); AssetsVerificationResult assetsResult = verifier.verify(result.getVerifiedURLResponses(), getConfiguration());//from w w w . j av a 2s. com System.out.println(assetsResult.getWorkingAssets().size() + " assets is ok, " + assetsResult.getNonWorkingAssets().size() + " is not"); for (AssetResponse resp : assetsResult.getNonWorkingAssets()) { builder.append(resp.getUrl()).append(",").append(resp.getReferer()).append(",") .append(StatusCode.toFriendlyName(resp.getResponseCode())).append("\n"); } Writer out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8")); out.write(builder.toString()); } catch (Exception e) { // TODO Auto-generated catch block System.err.println(e); } finally { if (out != null) try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block System.err.println(e); } } crawler.shutdown(); verifier.shutdown(); }
From source file:fr.univrouen.poste.services.ArchiveService.java
@Transactional(readOnly = true) public void archive(String destFolder) throws IOException, SQLException { List<PosteCandidature> posteCandidatures = PosteCandidature.findAllPosteCandidatures(); File destFolderFile = new File(destFolder); if (destFolderFile.mkdir()) { Writer csvGlobalWriter = new FileWriter(destFolder.concat("/candidatures.csv")); csvService.csvWrite(csvGlobalWriter, posteCandidatures); Writer statWriter = new FileWriter(destFolder.concat("/stat.txt")); StatBean stat = statService.stats(); statWriter.write(stat.toText()); statWriter.close(); final String[] header = new String[] { "id", "filename", "sendDate", "owner" }; final CellProcessor[] processors = getProcessors(); for (PosteCandidature posteCandidature : posteCandidatures) { String folderName = destFolder.concat("/"); String numEmploi = posteCandidature.getPoste().getNumEmploi(); numEmploi = numEmploi.replaceAll("[^a-zA-Z0-9.-]", "_"); folderName = folderName.concat(numEmploi).concat("/"); File folder = new File(folderName); folder.mkdir();/*from w w w . j av a 2 s.c o m*/ folderName = folderName.concat(posteCandidature.getRecevable() ? "Recevable" : "Non_Recevable") .concat("/"); folder = new File(folderName); folder.mkdir(); if (posteCandidature.getAuditionnable() != null) { folderName = folderName .concat(posteCandidature.getAuditionnable() ? "Auditionnable" : "Non_Auditionnable") .concat("/"); folder = new File(folderName); folder.mkdir(); } String nom = posteCandidature.getCandidat().getNom().replaceAll("[^a-zA-Z0-9.-]", "_"); String prenom = posteCandidature.getCandidat().getPrenom().replaceAll("[^a-zA-Z0-9.-]", "_"); String numCandidat = posteCandidature.getCandidat().getNumCandidat().replaceAll("[^a-zA-Z0-9.-]", "_"); folderName = folderName.concat(nom).concat("-"); folderName = folderName.concat(prenom).concat("-"); folderName = folderName.concat(numCandidat).concat("/"); folder = new File(folderName); folder.mkdir(); ICsvBeanWriter beanWriter = new CsvBeanWriter(new FileWriter(folderName.concat("metadata.csv")), CsvPreference.STANDARD_PREFERENCE); beanWriter.writeHeader(header); for (PosteCandidatureFile posteCandidatureFile : posteCandidature.getCandidatureFiles()) { String fileName = posteCandidatureFile.getId().toString().concat("-") .concat(posteCandidatureFile.getFilename()); String folderFileName = folderName.concat(fileName); File file = new File(folderFileName); file.createNewFile(); OutputStream outputStream = new FileOutputStream(file); InputStream inputStream = posteCandidatureFile.getBigFile().getBinaryFile().getBinaryStream(); IOUtils.copyLarge(inputStream, outputStream); ArchiveMetadataFileBean archiveMetadataFileBean = new ArchiveMetadataFileBean(fileName, posteCandidatureFile.getFilename(), posteCandidatureFile.getSendTime(), posteCandidature.getCandidat().getEmailAddress()); beanWriter.write(archiveMetadataFileBean, header, processors); } beanWriter.close(); if (!posteCandidature.getMemberReviewFiles().isEmpty()) { folderName = folderName.concat("Rapports_commission").concat("/"); folder = new File(folderName); folder.mkdir(); beanWriter = new CsvBeanWriter(new FileWriter(folderName.concat("metadata.csv")), CsvPreference.STANDARD_PREFERENCE); beanWriter.writeHeader(header); for (MemberReviewFile memberReviewFile : posteCandidature.getMemberReviewFiles()) { String fileName = memberReviewFile.getId().toString().concat("-") .concat(memberReviewFile.getFilename()); String folderFileName = folderName.concat(fileName); File file = new File(folderFileName); file.createNewFile(); OutputStream outputStream = new FileOutputStream(file); InputStream inputStream = memberReviewFile.getBigFile().getBinaryFile().getBinaryStream(); IOUtils.copyLarge(inputStream, outputStream); ArchiveMetadataFileBean archiveMetadataFileBean = new ArchiveMetadataFileBean(fileName, memberReviewFile.getFilename(), memberReviewFile.getSendTime(), memberReviewFile.getMember().getEmailAddress()); beanWriter.write(archiveMetadataFileBean, header, processors); } beanWriter.close(); } } } else { logger.error("Le rpertoire " + destFolder + " n'a pas pu tre cr. Vrifiez qu'il n'existe pas dj, que l'application a bien les droits de le crer, etc."); } }
From source file:com.epimorphics.lda.renderers.velocity.VelocityRendering.java
/** * Render the top-level template, given the result set and other state stored * in this rendering closure./* w w w. j ava2 s . c o m*/ * * @param os The output stream to write to */ protected void render(OutputStream os) { VelocityEngine ve = createVelocityEngine(); VelocityContext vc = createVelocityContext(this.bindings); Template t = null; try { t = ve.getTemplate(vr.templateName()); } catch (ResourceNotFoundException e) { ELog.debug(log, "could not find base template '%s'", vr.templateName()); ELog.debug(log, "current velocity path is '%s'", ve.getProperty(VELOCITY_FILE_RESOURCE_LOADER_PATH)); throw e; } try { Writer w = new OutputStreamWriter(os, "UTF-8"); t.merge(vc, w); w.close(); } catch (UnsupportedEncodingException e) { throw new BrokenException(e); } catch (IOException e) { throw new WrappedException(e); } }
From source file:edu.gcsc.vrl.jfreechart.JFExport.java
/** * Export jfreechart to image format. File must have an extension like jpg, * png, pdf, svg, eps. Otherwise export will fail. * * @param file Destination Filedescriptor * @param chart JFreechart/*from w w w.ja v a2 s .c o m*/ * @throws Exception */ public boolean export(File file, JFreeChart chart) throws Exception { /*Get extension from file - File must have one extension of jpg,png,pdf,svg,eps. Otherwise the export will fail. */ String ext = JFUtils.getExtension(file); // TODO - Make x,y variable int x, y; // Set size for image (jpg) x = 550; y = 470; int found = 0; // JPEG if (ext.equalsIgnoreCase("jpg")) { ChartUtilities.saveChartAsJPEG(file, chart, x, y); found++; } // PNG if (ext.equalsIgnoreCase("png")) { ChartUtilities.saveChartAsPNG(file, chart, x, y); found++; } // PDF if (ext.equalsIgnoreCase("pdf")) { //JRAbstractRenderer jfcRenderer = new JFreeChartRenderer(chart); // Use here size of r2d2 (see below, Rectangel replaced by Rectangle2D !) Rectangle pagesize = new Rectangle(x, y); Document document = new Document(pagesize, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file)); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(x, y); Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper()); // Draw doesn't works with Rectangle argument - use rectangle2D instead ! //chart.draw(g2, (java.awt.geom.Rectangle2D) new Rectangle(x,y)); Rectangle2D r2d2 = new Rectangle2D.Double(0, 0, x, y); chart.draw(g2, r2d2); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); found++; } // SVG if (ext.equalsIgnoreCase("svg")) { // When exporting to SVG don't forget this VERY important line: // svgGenerator.setSVGCanvasSize(new Dimension(width, height)); // Otherwise renderers will not know the size of the image. It will be drawn to the correct rectangle, but the image will not have a correct default siz // Get a DOMImplementation DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation(); org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null); SVGGraphics2D svgGenerator = new SVGGraphics2D(document); //chart.draw(svgGenerator,new Rectangle(x,y)); chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, x, y)); boolean useCSS = true; // we want to use CSS style attribute Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); svgGenerator.stream(out, useCSS); out.close(); found++; } if (ext.equalsIgnoreCase("eps")) { //Graphics2D g = new EpsGraphics2D(); FileOutputStream out = new FileOutputStream(file); //Writer out=new FileWriter(file); Graphics2D g = new EpsGraphics(file.getName(), out, 0, 0, x, y, ColorMode.COLOR_RGB); chart.draw(g, new Rectangle2D.Double(0, 0, x, y)); //Writer out=new FileWriter(file); out.write(g.toString().getBytes()); out.close(); found++; } if (found == 0) { throw new IllegalArgumentException("File format '" + ext + "' not supported!"); } return true; }
From source file:com.moss.appsnap.keeper.Keeper.java
public Keeper(final Url location) { log.info("Starting keeper for " + location); final DesktopIntegrationStrategy desktop = new Bootstrapper().discover(); final ProxyFactory proxyFactory = new ProxyFactory(new HessianProxyProvider()); final AppsnapService snap = proxyFactory.create(AppsnapService.class, location.toString()); AppsnapServiceInfo serviceInfo;//from w w w. ja v a 2 s.c om while (true) { try { serviceInfo = snap.serviceInfo(); break; } catch (Exception e) { log.error("Error talking to appsnap. Will try again in 5 seconds. The message was: " + e.getMessage(), e); try { Thread.sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } } } final File dataLocation = desktop.keeperDataDir(serviceInfo.id()); try { final File logOutput = new File(dataLocation, "log4j.log"); Logger.getRootLogger().addAppender(new FileAppender(new SimpleLayout(), logOutput.getAbsolutePath())); log.info("Configured logging to " + logOutput.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } log.info("Starting from " + dataLocation.getAbsolutePath()); Data data; try { data = new Data(dataLocation); } catch (Exception e1) { throw new RuntimeException(e1); } if (data.config.get() == null) { if (System.getProperty("dev-bootstrap", "false").equals("true")) { KeeperConfig config = new KeeperConfig(); data.config.put(config); } else { throw new NullPointerException("Keeper data has no config: have you run the installer?"); } } if (location == null) { throw new NullPointerException(); } guts = new Guts(serviceInfo, location, proxyFactory, snap, data, desktop); desktop.noLongerGutless(guts); final Poller poller = new Poller(guts, true); poller.start(); desktop.thePollerWasStartedAndHereItIs(poller); desktop.startLocalApiServer(new ApiMessageHandler() { final SocketFunction[] commands = new SocketFunction[] { new PollFunction(guts, poller), new InstallFunction(guts, poller), new ControlPanelLaunchFunction(guts), new LaunchFunction(guts, poller), new PingFuction() }; public void handle(ApiMessageConnection socket) { try { log.info("Opening connection"); StringBuilder input = new StringBuilder(); Reader r = new InputStreamReader(socket.in()); log.info("Reading input"); // char[] b = new char[1024]; // for(int x=r.read(b);x!=-1;x=r.read(b)){ // input.append(b, 0, x); // } for (int x = r.read(); x != -1 && x != '\n'; x = r.read()) { input.append((char) x); } // r.close(); log.info("Command: " + input); String commandName; String commandParams; int argsDelimiterPos = input.indexOf(" "); if (argsDelimiterPos != -1) { commandName = input.substring(0, argsDelimiterPos); commandParams = input.substring(argsDelimiterPos + 1); } else { commandName = input.toString(); commandParams = ""; } SocketFunction command = null; for (SocketFunction next : commands) { if (next.name().equals(commandName)) { command = next; } } String response; if (command == null) { response = ("Invalid command: " + commandName); } else { try { response = command.execute(commandParams); } catch (Exception e) { e.printStackTrace(); response = e.getClass().getSimpleName() + ":" + e.getMessage(); } } log.info("Sending response: " + response); Writer w = new OutputStreamWriter(socket.out()); w.write(response); w.write('\n'); w.flush(); w.close(); } catch (Throwable e) { e.printStackTrace(); } finally { socket.close(); } } }); }
From source file:com.streamsets.datacollector.restapi.TestRestApiAuthorization.java
private String startServer(boolean authzEnabled) throws Exception { int port = 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);/*from www. j a v a 2 s . c om*/ 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; }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.util.BeanToTextExporter.java
public static String beanListToText(final String type, final Writer out, final Map<String, String> columns, final List data, final DateFormat dateFormat) { CSVWriter writer = new CSVWriter(out); if ("tab".equals(type)) { writer = new CSVWriter(out, '\t', CSVWriter.NO_QUOTE_CHARACTER); }//from www . j ava 2s.c o m List<String> cols = new LinkedList<String>(); try { //Writing the column headers for (Map.Entry<String, String> e : columns.entrySet()) { cols.add(e.getValue()); } writer.writeNext((String[]) cols.toArray(new String[columns.size()])); cols.clear(); //Writing the data if (data != null) { for (Object o : data) { for (Map.Entry<String, String> e : columns.entrySet()) { final Object obj = getAndInvokeGetter(o, e.getKey()); String value = getExportString(obj, dateFormat); if ("tab".equals(type)) { value = value.replace("\t", " "); } cols.add(value); } writer.writeNext((String[]) cols.toArray(new String[columns.size()])); cols.clear(); } } writer.close(); out.flush(); out.close(); } catch (Exception e) { logger.debug(FancyExceptionLogger.printException(e)); return "An error occurred."; } return out.toString(); }
From source file:com.bstek.dorado.idesupport.RuleSetBuilderTest.java
public void testOutputAndParse() throws Exception { RuleTemplateManager ruleTemplateManager = getRuleTemplateBuilder().getRuleTemplateManager(); byte[] byteArray = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(out); try {//from w ww . j av a2s .c o m getRuleSetOutputter().output(writer, ruleTemplateManager); byteArray = out.toByteArray(); } finally { writer.close(); out.close(); } assertNotNull(byteArray); InputStream in = new ByteArrayInputStream(byteArray); try { RuleSet ruleSet = getRuleSetBuilder().buildRuleSet(in); assertNotNull(ruleSet); assertFalse(ruleSet.getRuleMap().isEmpty()); List<PackageInfo> packageInfos = ruleSet.getPackageInfos(); assertNotNull(packageInfos); assertTrue(!packageInfos.isEmpty()); Rule modelRule = ruleSet.getRule("Model"); assertNotNull(modelRule); Map<String, Child> children = modelRule.getChildren(); assertTrue(children.size() >= 3); Child dataTypeChild = children.get("DataType"); Rule dataTypeRule = dataTypeChild.getRule(); assertNotNull(dataTypeRule); assertEquals("DataType", dataTypeRule.getNodeName()); Child dataProviderChild = children.get("DataProvider"); Rule dataProviderRule = dataProviderChild.getRule(); assertNotNull(dataProviderRule); Rule propertyDefRule = ruleSet.getRule("PropertyDef"); assertNotNull(propertyDefRule); Child validatorChild = propertyDefRule.getChild("Validator"); assertNotNull(validatorChild); System.out.println("Children of ValidotorRule: "); Set<Rule> validatorRules = validatorChild.getConcreteRules(); for (Rule validatorRule : validatorRules) { System.out.println(validatorRule.getName() + " : " + validatorRule.getNodeName()); } Property mappingProperty = propertyDefRule.getProperty("mapping"); assertNotNull(mappingProperty); assertTrue(mappingProperty.getCompositeType() == CompositeType.Fixed); assertEquals(3, mappingProperty.getProperties().size()); Rule buttonRule = ruleSet.getRule("Button"); assertNotNull(buttonRule); Property property = buttonRule.getProperty("action"); assertNotNull(property); assertEquals("Action", property.getReference().getRule().getName()); Rule abstractButtonRule = ruleSet.getRule("AbstractButton"); assertNotNull(abstractButtonRule); assertTrue(ArrayUtils.indexOf(buttonRule.getParents(), abstractButtonRule) >= 0); boolean hasButtonRule = false; Rule[] concretButtonRules = abstractButtonRule.getSubRules(); for (Rule concretButtonRule : concretButtonRules) { String name = concretButtonRule.getName(); if ("Button".equals(name)) { hasButtonRule = true; } } assertTrue(hasButtonRule); Rule controlRule = ruleSet.getRule("Control_1"); assertNotNull(controlRule); assertTrue(ArrayUtils.indexOf(abstractButtonRule.getParents(), controlRule) >= 0); boolean hasAbstractButtonRule = false; Rule[] concretControlRules = controlRule.getSubRules(); for (Rule concretControlRule : concretControlRules) { String name = concretControlRule.getName(); if ("AbstractButton".equals(name)) { hasAbstractButtonRule = true; } } assertTrue(hasAbstractButtonRule); Rule floatPanelRule = ruleSet.getRule("FloatPanel"); assertNotNull(floatPanelRule); assertNotNull(floatPanelRule.getChild("Children")); assertNotNull(floatPanelRule.getChild("Tools")); assertNotNull(floatPanelRule.getChild("Buttons")); Property animateTargetProperty = floatPanelRule.getProperty("animateTarget"); assertNotNull(animateTargetProperty); assertFalse(animateTargetProperty.isVisible()); Rule viewRule = ruleSet.getRule("View"); for (Child child : viewRule.getChildren().values()) { Rule childRule = child.getRule(); System.out.println(childRule.getName() + " : " + childRule.getNodeName()); } Rule dataTreeGridRule = ruleSet.getRule("DataTreeGrid"); assertNotNull(dataTreeGridRule); property = dataTreeGridRule.getProperty("dataSet"); assertNotNull(property); assertEquals("DataSet", property.getReference().getRule().getName()); Rule treeRule = ruleSet.getRule("Tree"); assertNotNull(treeRule); Rule customDropDownRule = ruleSet.getRule("CustomDropDown"); assertNotNull(customDropDownRule); Child child = customDropDownRule.getChild("Control"); assertNotNull(child); System.out.println("Children of CustomDropDown: "); Set<Rule> concreteRules = child.getConcreteRules(); for (Rule concreteRule : concreteRules) { System.out.println(concreteRule.getName() + " : " + concreteRule.getNodeName()); } } finally { in.close(); } }
From source file:com.wesley.urban_cuts.services.barber_services.Write_to_file.java
public void write_to_file(String data1, String data2, String data3) { Date d = new Date(); Writer writer = null; try {/*w ww . jav a2 s.co m*/ writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("Urban Cuts Log" + ".txt"), "utf-8")); writer.append(""); writer.append(data1 + " " + data2 + " " + data3 + " " + d); } catch (IOException ex) { System.out.println("couldn't write to file"); } finally { try { writer.close(); } catch (Exception ex) { /*ignore*/} } }