List of usage examples for java.io Writer close
public abstract void close() throws IOException;
From source file:it.unimi.dsi.util.Properties.java
/** Saves the configuration to the specified file. * /*w w w.j a v a 2 s. c o m*/ * @param filename a file name. */ public void save(final CharSequence filename) throws ConfigurationException, IOException { final Writer w = new OutputStreamWriter(new FileOutputStream(filename.toString()), "UTF-8"); super.save(w); w.close(); }
From source file:com.shootoff.session.io.JSONSessionWriter.java
@SuppressWarnings("unchecked") @Override/*from w ww. j a va 2 s.c o m*/ public void visitEnd() { JSONObject session = new JSONObject(); session.put("cameras", cameras); Writer file = null; try { file = new OutputStreamWriter(new FileOutputStream(sessionFile), "UTF-8"); file.write(session.toJSONString()); file.flush(); } catch (IOException e) { logger.error("Error writing JSON session", e); } finally { try { if (file != null) file.close(); } catch (IOException e) { logger.error("Error closing JSON session", e); } } }
From source file:com.streamsets.datacollector.restapi.TestRestApiAuthorization.java
@Before public void setup() throws Exception { server = null;//ww w. ja v a 2 s. c o m 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"); }
From source file:it.jugpadova.controllers.EventController.java
@RequestMapping public ModelAndView json(HttpServletRequest req, HttpServletResponse res) throws Exception { try {/*from www. j a va2 s . c o m*/ EventSearch eventSearch = buildEventSearch(req); List<Event> events = eventBo.search(eventSearch); String json = feedsBo.buildJson(events, Utilities.getBaseUrl(req), true); // flush it in the res res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0, no-store"); res.setHeader("Pragma", "public, no-cache"); res.setDateHeader("Expires", 0); res.setContentType("application/json"); res.setContentLength(json.getBytes().length); res.setCharacterEncoding("UTF-8"); ServletOutputStream resOutputStream = res.getOutputStream(); Writer writer = new OutputStreamWriter(resOutputStream, "UTF-8"); writer.write(json); writer.flush(); writer.close(); } catch (Exception exception) { logger.error("Error producing JSON", exception); throw exception; } return null; }
From source file:edina.eframework.gefcdemo.controllers.ProcessErosionController.java
/** * Brokers the WPS request and response. Supports two different WPS requests, * the landcover preview and the process soil erosion model requests. * /*from w w w . j ava 2s. c o m*/ * @param params parameters used when calculating the soil erosion model * @param wpsResponse results from the WPS process are written to this object * @param template the VM template to use to generate the WPS request * @param wpsOutputFile the filename to write the TIFF result file * @throws IOException * @throws JAXBException */ private void generateWpsRequest(SoilErosionWps params, WpsResponse wpsResponse, String template, String wpsOutputFile) throws IOException, JAXBException { Writer wpsRequest = new StringWriter(); Map<String, Object> velocityMap = new HashMap<String, Object>(); velocityMap.put("params", params); VelocityEngineUtils.mergeTemplate(velocityEngine, template, velocityMap, wpsRequest); wpsRequest.close(); log.debug(wpsRequest.toString()); log.debug("Submitting to " + wpsServer); RequestEntity entity = null; try { entity = new StringRequestEntity(wpsRequest.toString(), "text/xml", "UTF-8"); } catch (UnsupportedEncodingException e) { throw new MalformedURLException("Apparantly 'UTF-8' is an unsupported encoding type."); } PostMethod post = new PostMethod(wpsServer.toString()); post.setRequestEntity(entity); HttpClient client = new HttpClient(new SimpleHttpConnectionManager()); client.getHttpConnectionManager().getParams().setSoTimeout(0); client.getHttpConnectionManager().getParams().setConnectionTimeout(0); client.executeMethod(post); JAXBContext jaxbContext = JAXBContext.newInstance("edina.eframework.gefcdemo.generated.wps"); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); ExecuteResponse executeResponse = null; // First save post data into a String so we can log any potential errors. // Response isn't very large from the WPS so this shouldn't be a problem. // Trying to access post data if a direct InputStream is passed to unmarshal // doesn't work. String postData = post.getResponseBodyAsString(); try { executeResponse = (ExecuteResponse) unmarshaller .unmarshal(new ByteArrayInputStream(postData.getBytes())); } catch (ClassCastException e) { log.error("Error from WPS:\n" + postData); throw e; } //executeResponse.getStatus().getProcessAccepted(); // TODO check for failed String resultUrl = executeResponse.getProcessOutputs().getOutput().get(0).getReference().getHref(); log.debug("Output " + resultUrl); wpsResponse.setOutputUrl(new URL(resultUrl)); wpsResponse.setOutputId(resultUrl.substring(resultUrl.lastIndexOf("id=") + 3, resultUrl.length())); wpsResponse.setStatus(200); // Save the WPS output data to a file mapserver can use File resultOutputFile = new File(wpsOutputFile); resultOutputFile.getParentFile().mkdirs(); FileOutputStream resultFileStream = new FileOutputStream(resultOutputFile); InputStream resultInputFile = null; try { resultInputFile = wpsResponse.getOutputUrl().openStream(); byte[] buffer = new byte[4096]; int i; while ((i = resultInputFile.read(buffer)) != -1) { resultFileStream.write(buffer, 0, i); } resultFileStream.flush(); } finally { try { resultInputFile.close(); } catch (Exception e) { } try { resultFileStream.close(); } catch (Exception e) { } } log.debug("Result saved to " + resultOutputFile); }
From source file:com.uber.hoodie.common.model.HoodieTestUtils.java
public static void writeRecordsToLogFiles(FileSystem fs, String basePath, Schema schema, List<HoodieRecord> updatedRecords) { Map<HoodieRecordLocation, List<HoodieRecord>> groupedUpdated = updatedRecords.stream() .collect(Collectors.groupingBy(HoodieRecord::getCurrentLocation)); groupedUpdated.entrySet().forEach(s -> { HoodieRecordLocation location = s.getKey(); String partitionPath = s.getValue().get(0).getPartitionPath(); Writer logWriter; try {/*from w w w . j a v a2s . c om*/ logWriter = HoodieLogFormat.newWriterBuilder().onParentPath(new Path(basePath, partitionPath)) .withFileExtension(HoodieLogFile.DELTA_EXTENSION).withFileId(location.getFileId()) .overBaseCommit(location.getCommitTime()).withFs(fs).build(); Map<HoodieLogBlock.HeaderMetadataType, String> header = Maps.newHashMap(); header.put(HoodieLogBlock.HeaderMetadataType.INSTANT_TIME, location.getCommitTime()); header.put(HoodieLogBlock.HeaderMetadataType.SCHEMA, schema.toString()); logWriter.appendBlock(new HoodieAvroDataBlock(s.getValue().stream().map(r -> { try { GenericRecord val = (GenericRecord) r.getData().getInsertValue(schema).get(); HoodieAvroUtils.addHoodieKeyToRecord(val, r.getRecordKey(), r.getPartitionPath(), ""); return (IndexedRecord) val; } catch (IOException e) { return null; } }).collect(Collectors.toList()), header)); logWriter.close(); } catch (Exception e) { fail(e.toString()); } }); }
From source file:com.moss.appsnap.keeper.windows.MSWindowsAppHandler.java
@Override public void handleInstall(boolean daemon, final ResolvedJavaLaunchSpec launch) { // write exe, port and params try {/*from w ww .ja v a2s .co m*/ daemonFsLayout.mkdirs(); if (!installDirPath.exists() && !installDirPath.mkdirs()) { throw new RuntimeException("Could not create directory: " + installDirPath.getAbsolutePath()); } ShellLink lnk = new ShellLink(); lnk.setWorkingDir(installDirPath.getAbsolutePath()); if (daemon) { try { MSWindowsDesktopIntegrationStrategy.writeDaemonLauncher(daemonLauncherExe); } catch (Throwable e) { log.warn( "There was an error copying the daemon launcher exe. This is expected if the keeper just launched.", e); } final File javaw = resolveFileFromPath("javaw.exe"); final String args; { StringBuilder line = launchArgs(launch); args = line.toString(); System.out.println("Using line: " + line); // String regex = "\""; // String replacement = "\\\\\""; // arg = line.toString().replaceAll(regex, replacement); } System.out.println("Using arg: " + args); { Writer w = new FileWriter(launchFilePath); w.write("\"" + javaw.getAbsolutePath() + "\" " + args + ""); w.close(); } // // lnk.setLinkTarget(daemonFsLayout.daemonLauncherExe.getAbsolutePath()); // lnk.setCommandLineArguments("\"" + arg + "\""); lnk.setLinkTarget(daemonLauncherExe); String id = info.id().toString(); String name = guts.serviceInfo.name() + "-keeper-" + id.substring(id.length() - 4) + ".lnk"; lnk.write(new File(fsLayout.startupMenu, name)); } else { MSWindowsDesktopIntegrationStrategy.writeKeeperTalker(appLauncherExe); { Writer w = new FileWriter(messagePath); w.write("LAUNCH " + info.id()); w.close(); } lnk.setLinkTarget(appLauncherExe.getAbsolutePath()); // lnk.setCommandLineArguments("\"LAUNCH " + info.id() + "\""); String fileName = info.name() + ".lnk"; lnk.write(new File(fsLayout.desktop, fileName)); lnk.write(new File(daemonFsLayout.daemonMenu, fileName)); } // // writeLaunchScript(daemon, line.toString(), scriptLocation, fsMap.fifoSockets); // // if(daemon){ // log.info("Writing " + info.name() + "(" + info.id() + ") to gnome session"); // addToGnomeSession(scriptLocation); // }else{ // log.info("Writing " + info.name() + "(" + info.id() + " to applications menu"); // addToApplicationsMenu(info.name(), info.id(), scriptLocation, fsMap); // } // } catch (IOException e) { throw new RuntimeException(e); } }
From source file:co.cask.cdap.app.deploy.SandboxJVM.java
/** * Main class within the object./*from ww w . j av a2 s . co m*/ * * @param args specified on command line. * @return 0 if successfull; otherwise non-zero. */ public int doMain(String[] args) { String jarFilename; File outputFile; String locationFactory; String id; LocationFactory lf; CommandLineParser parser = new GnuParser(); Options options = new Options(); options.addOption("i", "id", true, "Account ID"); options.addOption("j", "jar", true, "Application JAR"); options.addOption("f", "locfactory", true, "Location Factory (LOCAL or DISTRIBUTED)"); options.addOption("o", "output", true, "Output"); // Check all the options of command line try { CommandLine line = parser.parse(options, args); if (!line.hasOption("jar")) { LOG.error("Application JAR not specified."); return -1; } if (!line.hasOption("output")) { LOG.error("Output file not specified."); return -1; } if (!line.hasOption("id")) { LOG.error("Account id not specified."); return -1; } if (!line.hasOption("locfactory")) { LOG.error("Location factory not specified."); return -1; } jarFilename = line.getOptionValue("jar"); outputFile = new File(line.getOptionValue("output")); id = line.getOptionValue("id"); locationFactory = line.getOptionValue("locfactory"); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SandboxJVM", options); return -1; } // Load the JAR using the JAR class load and load the manifest file. File unpackedJarDir = Files.createTempDir(); try { Application app; try { if ("LOCAL".equals(locationFactory)) { lf = new LocalLocationFactory(); } else if ("DISTRIBUTED".equals(locationFactory)) { lf = new HDFSLocationFactory(new Configuration()); } else { LOG.error("Unknown location factory specified"); return -1; } Program archive = Programs.createWithUnpack(lf.create(jarFilename), unpackedJarDir); Object appMain = archive.getMainClass().newInstance(); if (!(appMain instanceof Application)) { LOG.error(String.format("Application main class is of invalid type: %s", appMain.getClass().getName())); return -1; } app = (Application) appMain; } catch (Exception e) { LOG.error(e.getMessage()); return -1; } // Now, we are ready to call configure on application. // Setup security manager, this setting allows only output file to be written. // Nothing else can be done from here on other than creating that file. ApplicationSecurity.builder().add(new FilePermission(outputFile.getAbsolutePath(), "write")).apply(); // Now, we call configure, which returns application specification. DefaultAppConfigurer configurer = new DefaultAppConfigurer(app); app.configure(configurer, new ApplicationContext()); ApplicationSpecification specification = configurer.createApplicationSpec(); // Convert the specification to JSON. // We write the Application specification to output file in JSON format. try { Writer writer = Files.newWriter(outputFile, Charsets.UTF_8); try { // TODO: The SchemaGenerator should be injected. ApplicationSpecificationAdapter.create(new ReflectionSchemaGenerator()).toJson(specification, writer); } finally { writer.close(); } } catch (IOException e) { LOG.error("Error writing to file {}. {}", outputFile, e.getMessage()); return -1; } } finally { try { FileUtils.deleteDirectory(unpackedJarDir); } catch (IOException e) { LOG.warn("Error deleting temp unpacked jar directory: {}", unpackedJarDir.getAbsolutePath(), e); } } return 0; }
From source file:com.sun.syndication.propono.atom.server.AtomServlet.java
/** * Handles an Atom POST by calling handler to identify URI, reading/parsing * data, calling handler and writing results to response. *//* ww w . j av a2s . co m*/ protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.debug("Entering"); AtomHandler handler = createAtomRequestHandler(req, res); String userName = handler.getAuthenticatedUsername(); if (userName != null) { AtomRequest areq = new AtomRequestImpl(req); try { if (handler.isCollectionURI(areq)) { if (req.getContentType().startsWith("application/atom+xml")) { // parse incoming entry Entry entry = Atom10Parser.parseEntry( new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")), null); // call handler to post it Entry newEntry = handler.postEntry(areq, entry); // set Location and Content-Location headers for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) { Link link = (Link) it.next(); if ("edit".equals(link.getRel())) { res.addHeader("Location", link.getHrefResolved()); break; } } for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) { Link link = (Link) it.next(); if ("alternate".equals(link.getRel())) { res.addHeader("Content-Location", link.getHrefResolved()); break; } } // write entry back out to response res.setStatus(HttpServletResponse.SC_CREATED); res.setContentType("application/atom+xml; type=entry; charset=utf-8"); Writer writer = res.getWriter(); Atom10Generator.serializeEntry(newEntry, writer); writer.close(); } else if (req.getContentType() != null) { // get incoming title and slug from HTTP header String title = areq.getHeader("Title"); // create new entry for resource, set title and type Entry resource = new Entry(); resource.setTitle(title); Content content = new Content(); content.setType(areq.getContentType()); resource.setContents(Collections.singletonList(content)); // hand input stream off to hander to post file Entry newEntry = handler.postMedia(areq, resource); // set Location and Content-Location headers for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) { Link link = (Link) it.next(); if ("edit".equals(link.getRel())) { res.addHeader("Location", link.getHrefResolved()); break; } } for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) { Link link = (Link) it.next(); if ("alternate".equals(link.getRel())) { res.addHeader("Content-Location", link.getHrefResolved()); break; } } res.setStatus(HttpServletResponse.SC_CREATED); res.setContentType("application/atom+xml; type=entry; charset=utf-8"); Writer writer = res.getWriter(); Atom10Generator.serializeEntry(newEntry, writer); writer.close(); } else { res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "No content-type specified in request"); } } else { res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid collection specified in request"); } } catch (AtomException ae) { res.sendError(ae.getStatus(), ae.getMessage()); log.debug("ERROR processing POST", ae); } catch (Exception e) { res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); log.debug("ERROR processing POST", e); } } else { res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\""); res.sendError(HttpServletResponse.SC_UNAUTHORIZED); } log.debug("Exiting"); }
From source file:functionalTests.vfsprovider.TestProActiveProviderAutoclosing.java
@Test public void testOutputStreamOpenWriteAutocloseWrite() throws Exception { final FileObject fo = openFileObject("out.txt"); final Writer writer = openWriter(fo); try {//from www .j a v a2s. c om writer.write("abc"); Thread.sleep(SLEEP_TIME); writer.write("def"); } finally { writer.close(); } assertContentEquals(fo, "abcdef"); fo.close(); }