List of usage examples for java.nio.file StandardOpenOption TRUNCATE_EXISTING
StandardOpenOption TRUNCATE_EXISTING
To view the source code for java.nio.file StandardOpenOption TRUNCATE_EXISTING.
Click Source Link
From source file:io.seqware.pipeline.plugins.FileProvenanceQueryTool.java
@Override public ReturnValue do_run() { Path randomTempDirectory = null; Path originalReport = null;//from w w w . j a va 2 s .c o m Path bulkImportFile = null; try { if (options.has(this.inFileSpec)) { originalReport = FileSystems.getDefault().getPath(options.valueOf(inFileSpec)); } else { originalReport = populateOriginalReportFromWS(); } List<String> headers; List<Boolean> numericDataType; // construct column name and datatypes // convert file provenance report into derby bulk load format try (BufferedReader originalReader = Files.newBufferedReader(originalReport, Charset.defaultCharset())) { // construct column name and datatypes String headerLine = originalReader.readLine(); headers = Lists.newArrayList(); numericDataType = Lists.newArrayList(); for (String column : headerLine.split("\t")) { String editedColumnName = StringUtils.lowerCase(column).replaceAll(" ", "_").replaceAll("-", "_"); headers.add(editedColumnName); // note that Parent Sample SWID is a silly column that has colons in it numericDataType.add( !editedColumnName.contains("parent_sample") && (editedColumnName.contains("swid"))); } bulkImportFile = Files.createTempFile("import", "txt"); try (BufferedWriter derbyImportWriter = Files.newBufferedWriter(bulkImportFile, Charset.defaultCharset())) { Log.debug("Bulk import file written to " + bulkImportFile.toString()); while (originalReader.ready()) { String line = originalReader.readLine(); StringBuilder builder = new StringBuilder(); int i = 0; for (String colValue : line.split("\t")) { if (i != 0) { builder.append("\t"); } if (numericDataType.get(i)) { if (!colValue.trim().isEmpty()) { builder.append(colValue); } } else { // assume that this is a string // need to double quotes to preserve them, see // https://db.apache.org/derby/docs/10.4/tools/ctoolsimportdefaultformat.html builder.append("\"").append(colValue.replaceAll("\"", "\"\"")).append("\""); } i++; } derbyImportWriter.write(builder.toString()); derbyImportWriter.newLine(); } } } randomTempDirectory = Files.createTempDirectory("randomFileProvenanceQueryDir"); // try using in-memory for better performance String protocol = "jdbc:h2:"; if (options.has(useH2InMemorySpec)) { protocol = protocol + "mem:"; } Connection connection = spinUpEmbeddedDB(randomTempDirectory, "org.h2.Driver", protocol); // drop table if it exists already (running in IDE?) Statement dropTableStatement = null; try { dropTableStatement = connection.createStatement(); dropTableStatement.executeUpdate("DROP TABLE " + TABLE_NAME); } catch (SQLException e) { Log.debug("Report table didn't exist (normal)"); } finally { DbUtils.closeQuietly(dropTableStatement); } // create table creation query StringBuilder tableCreateBuilder = new StringBuilder(); // tableCreateBuilder tableCreateBuilder.append("CREATE TABLE " + TABLE_NAME + " ("); for (int i = 0; i < headers.size(); i++) { if (i != 0) { tableCreateBuilder.append(","); } if (numericDataType.get(i)) { tableCreateBuilder.append(headers.get(i)).append(" INT "); } else { tableCreateBuilder.append(headers.get(i)).append(" VARCHAR "); } } tableCreateBuilder.append(")"); bulkImportH2(tableCreateBuilder, connection, bulkImportFile); // query the database and dump the results to try (BufferedWriter outputWriter = Files.newBufferedWriter(Paths.get(options.valueOf(outFileSpec)), Charset.defaultCharset(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { // query the database and dump the results to QueryRunner runner = new QueryRunner(); List<Map<String, Object>> mapList = runner.query(connection, options.valueOf(querySpec), new MapListHandler()); // output header if (mapList.isEmpty()) { Log.fatal("Query had no results"); System.exit(-1); } StringBuilder builder = new StringBuilder(); for (String columnName : mapList.get(0).keySet()) { if (builder.length() != 0) { builder.append("\t"); } builder.append(StringUtils.lowerCase(columnName)); } outputWriter.append(builder); outputWriter.newLine(); for (Map<String, Object> rowMap : mapList) { StringBuilder rowBuilder = new StringBuilder(); for (Entry<String, Object> e : rowMap.entrySet()) { if (rowBuilder.length() != 0) { rowBuilder.append("\t"); } rowBuilder.append(e.getValue()); } outputWriter.append(rowBuilder); outputWriter.newLine(); } } DbUtils.closeQuietly(connection); Log.stdoutWithTime("Wrote output to " + options.valueOf(outFileSpec)); return new ReturnValue(); } catch (IOException | SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { throw new RuntimeException(ex); } finally { if (originalReport != null) { FileUtils.deleteQuietly(originalReport.toFile()); } if (bulkImportFile != null) { FileUtils.deleteQuietly(bulkImportFile.toFile()); } if (randomTempDirectory != null && randomTempDirectory.toFile().exists()) { FileUtils.deleteQuietly(randomTempDirectory.toFile()); } } }
From source file:org.basinmc.maven.plugins.bsdiff.DiffMojo.java
/** * Retrieves a remote artifact and stores it in a pre-defined cache directory. */// w ww . ja v a 2 s. c o m @Nonnull private Path retrieveSourceFile() throws MojoFailureException { HttpClient client = HttpClients.createMinimal(); String fileName; { String path = this.sourceURL.getPath(); int i = path.lastIndexOf('/'); fileName = path.substring(i + 1); } try { this.getLog().info("Downloading source artifact from " + this.sourceURL.toExternalForm()); HttpGet request = new HttpGet(this.sourceURL.toURI()); HttpResponse response = client.execute(request); if (response.containsHeader("Content-Disposition")) { String disposition = response.getLastHeader("Content-Disposition").getValue(); Matcher matcher = DISPOSITION_PATTERN.matcher(disposition); if (matcher.matches()) { fileName = URLDecoder.decode(matcher.group(1), "UTF-8"); } } this.getLog().info("Storing " + fileName + " in cache directory"); Path outputPath = this.cacheDirectory.toPath().resolve(fileName); if (!Files.isDirectory(outputPath.getParent())) { Files.createDirectories(outputPath.getParent()); } try (InputStream inputStream = response.getEntity().getContent()) { try (ReadableByteChannel inputChannel = Channels.newChannel(inputStream)) { try (FileChannel outputChannel = FileChannel.open(outputPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { outputChannel.transferFrom(inputChannel, 0, Long.MAX_VALUE); } } } return outputPath; } catch (IOException ex) { throw new MojoFailureException("Failed to read/write source artifact: " + ex.getMessage(), ex); } catch (URISyntaxException ex) { throw new MojoFailureException("Invalid source URI: " + ex.getMessage(), ex); } }
From source file:org.ballerinalang.containers.docker.impl.DefaultBallerinaDockerClient.java
private String createImageFromSingleConfig(String serviceName, String dockerEnv, String ballerinaConfig, boolean isService, String imageName, String imageVersion) throws BallerinaDockerClientException, IOException, InterruptedException { imageName = getImageName(serviceName, imageName, imageVersion); // 1. Create a tmp docker context Path tmpDir = prepTempDockerfileContext(); // 2. Create a .bal file inside context/files Path ballerinaFile = Files.createFile( Paths.get(tmpDir + File.separator + PATH_FILES + File.separator + serviceName + PATH_BAL_FILE_EXT)); Files.write(ballerinaFile, ballerinaConfig.getBytes(Charset.defaultCharset()), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); // 3. Create a docker image from the temp context String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssXX").format(new Date()); String buildArgs = "{\"" + ENV_SVC_MODE + "\":\"" + String.valueOf(isService) + "\", " + "\"" + ENV_FILE_MODE + "\":\"true\", \"BUILD_DATE\":\"" + timestamp + "\"}"; buildImage(dockerEnv, imageName, tmpDir, buildArgs); // 4. Cleanup cleanupTempDockerfileContext(tmpDir); return getImage(imageName, dockerEnv); }
From source file:org.ballerinalang.test.packaging.ModuleBuildTestCase.java
@Test(description = "Test building a module which has xml content in the test package") public void testBuildWithXML() throws BallerinaTestException, IOException { Path projectPath = tempProjectDirectory.resolve("sixthTestProject"); initProject(projectPath, SINGLE_PKG_PROJECT_OPTS); // Replace the content of the test file String testContent = "import ballerina/test;\n" + "import ballerina/io;\n" + "\n" + "xmlns \"http://ballerina.com/aa\" as ns0;\n" + "\n" + "# Test function\n" + "\n" + "@test:Config\n" + "function testFunction () {\n" + " io:println(\"I'm in test function!\");\n" + " test:assertTrue(true , msg = \"Failed!\");\n" + "\n" + " xmlns \"http://ballerina.com/bb\" as ns1;\n" + " xmlns \"http://ballerina.com/default\";\n" + "\n" + " io:println(ns0:foo);\t\n" + "}\n"; Files.write(projectPath.resolve("foo").resolve("tests").resolve("main_test.bal"), testContent.getBytes(), StandardOpenOption.TRUNCATE_EXISTING); balClient.runMain("build", new String[0], envVariables, new String[0], new LogLeecher[] {}, projectPath.toString());// w w w . j a v a2 s .c om Path genPkgPath = Paths.get(ProjectDirConstants.DOT_BALLERINA_DIR_NAME, ProjectDirConstants.DOT_BALLERINA_REPO_DIR_NAME, ORG_NAME, "foo", VERSION); Assert.assertTrue(Files.exists(projectPath.resolve(genPkgPath).resolve("foo.zip"))); Assert.assertTrue(Files.exists(projectPath.resolve("target").resolve("foo.balx"))); }
From source file:com.diffplug.gradle.FileMisc.java
/** Concats the first files and writes them to the last file. */ public static void concat(Iterable<File> toMerge, File dst) throws IOException { try (FileChannel dstChannel = FileChannel.open(dst.toPath(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { for (File file : toMerge) { try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { FileChannel channel = raf.getChannel(); dstChannel.write(channel.map(FileChannel.MapMode.READ_ONLY, 0, raf.length())); }/*from w w w . ja v a 2 s . com*/ } } }
From source file:sonicScream.models.Script.java
/** * Modifies the relevant properties to turn this script into a "local" script rather than a "VPK" script, and writes * the modified script out to disk.//from ww w . j a v a 2 s .co m */ public void convertToLocalScript() throws IOException { SettingsService settings = (SettingsService) ServiceLocator.getService(SettingsService.class); String profileName = settings.getSetting(Constants.SETTING_ACTIVE_PROFILE); Path scriptDestPath = Paths.get(SettingsUtils.getProfileDirectory(profileName).toString(), "sonic-scream", _vpkPath.toString().replace(".vsndevts_c", ".vsndevts")); Files.createDirectories(scriptDestPath.getParent()); this._localPath = scriptDestPath.toString(); this._isCustom = true; this._rawFileName = _rawFileName.replace(".vsndevts_c", ".vsndevts"); updateRootNodeWithSimpleTree(); if (!Files.exists(scriptDestPath)) { Files.createFile(scriptDestPath); } //Actually write the current script out to file now Files.write(scriptDestPath, getScriptAsString().getBytes(), StandardOpenOption.TRUNCATE_EXISTING); }
From source file:org.schedulesdirect.grabber.ScheduleTask.java
protected Map<String, Collection<String>> getStaleStationIds() { Map<String, Collection<String>> staleIds = new HashMap<>(); DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.SCHEDULE_MD5S, clnt.getHash(), clnt.getUserAgent(), clnt.getBaseUrl()); JSONArray data = new JSONArray(); for (int i = 0; i < this.req.length(); ++i) { JSONObject o = new JSONObject(); o.put("stationID", this.req.getString(i)); data.put(o);/*from w ww. java 2s. c om*/ } try { JSONObject result = Config.get().getObjectMapper().readValue(req.submitForJson(data), JSONObject.class); if (!JsonResponseUtils.isErrorResponse(result)) { Iterator<?> idItr = result.keys(); while (idItr.hasNext()) { String stationId = idItr.next().toString(); boolean schedFileExists = Files .exists(vfs.getPath("schedules", String.format("%s.txt", stationId))); Path cachedMd5File = vfs.getPath("md5s", String.format("%s.txt", stationId)); JSONObject cachedMd5s = Files.exists(cachedMd5File) ? Config.get().getObjectMapper() .readValue(new String(Files.readAllBytes(cachedMd5File), ZipEpgClient.ZIP_CHARSET.toString()), JSONObject.class) : new JSONObject(); JSONObject stationInfo = result.getJSONObject(stationId); Iterator<?> dateItr = stationInfo.keys(); while (dateItr.hasNext()) { String date = dateItr.next().toString(); JSONObject dateInfo = stationInfo.getJSONObject(date); if (!schedFileExists || isScheduleStale(dateInfo, cachedMd5s.optJSONObject(date))) { Collection<String> dates = staleIds.get(stationId); if (dates == null) { dates = new ArrayList<String>(); staleIds.put(stationId, dates); } dates.add(date); if (LOG.isDebugEnabled()) LOG.debug(String.format("Station %s/%s queued for refresh!", stationId, date)); } else if (LOG.isDebugEnabled()) LOG.debug(String.format("Station %s is unchanged on the server; skipping it!", stationId)); } Files.write(cachedMd5File, stationInfo.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } } } catch (Throwable t) { Grabber.failedTask = true; LOG.error("Error processing cache; returning partial stale list!", t); } return staleIds; }
From source file:org.roda.core.plugins.plugins.base.ExportAIPPlugin.java
private Report exportMultiZip(List<AIP> aips, Path outputPath, Report report, ModelService model, IndexService index, StorageService storage, SimpleJobPluginInfo jobPluginInfo, Job job) { for (AIP aip : aips) { LOGGER.debug("Exporting AIP {} to ZIP", aip.getId()); OutputStream os = null;//from ww w.j av a2 s . c o m String error = null; try { Path zip = outputPath.resolve(aip.getId() + ".zip"); if (FSUtils.exists(zip) && removeIfAlreadyExists) { Files.delete(zip); } else if (FSUtils.exists(zip) && !removeIfAlreadyExists) { error = "File " + zip.toString() + " already exists"; } if (error == null) { os = Files.newOutputStream(zip, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); Directory directory = storage.getDirectory(ModelUtils.getAIPStoragePath(aip.getId())); ConsumesOutputStream cos = DownloadUtils.download(storage, directory); cos.consumeOutputStream(os); } } catch (Exception e) { LOGGER.error("Error exporting AIP " + aip.getId() + ": " + e.getMessage()); error = e.getMessage(); } finally { if (os != null) { IOUtils.closeQuietly(os); } } Report reportItem = PluginHelper.initPluginReportItem(this, aip.getId(), AIP.class, AIPState.ACTIVE); if (error != null) { reportItem.setPluginState(PluginState.FAILURE) .setPluginDetails("Export AIP did not end successfully: " + error); jobPluginInfo.incrementObjectsProcessedWithFailure(); } else { reportItem.setPluginState(PluginState.SUCCESS).setPluginDetails("Export AIP ended successfully"); jobPluginInfo.incrementObjectsProcessedWithSuccess(); } report.addReport(reportItem); PluginHelper.updatePartialJobReport(this, model, reportItem, true, job); } return report; }
From source file:org.ballerinalang.test.packaging.ModuleBuildTestCase.java
/** * Building an empty project without any modules. * * @throws BallerinaTestException When an error occurs executing the command. *//* w w w. ja v a 2s.c o m*/ @Test(description = "Test building a project with an invalid manifest file") public void testBuildOnInvalidManifest() throws BallerinaTestException, IOException { Path projectPath = tempProjectDirectory.resolve("invalidManifest"); initProject(projectPath, EMPTY_PROJECT_OPTS); String invalidContent = "[project]\n org-name = \"integrationtests\"\n version = \"1.0.0"; Files.write(projectPath.resolve("Ballerina.toml"), invalidContent.getBytes(), StandardOpenOption.TRUNCATE_EXISTING); LogLeecher clientLeecher = new LogLeecher("error: invalid toml syntax at Ballerina.toml:3", LogLeecher.LeecherType.ERROR); balClient.runMain("build", new String[0], envVariables, new String[0], new LogLeecher[] { clientLeecher }, projectPath.toString()); clientLeecher.waitForText(3000); }
From source file:com.mhs.hboxmaintenanceserver.HBoxMaintenanceServer.java
public void start() { try {/*ww w .j a v a 2 s . c o m*/ hbmws = new HBoxMaintenanceWebsocketServer(this, websocket_port); hbmws.start(); hbmws.sendListOfHBoxBy_Interval(); httpServer = HttpServer.createSimpleServer(null, webserver_port); AccessLogBuilder logBuilder = new AccessLogBuilder(DefaultConfig.GRIZZLY_LOG); logBuilder.rotatedDaily().instrument(httpServer.getServerConfiguration()); HBoxMaintenanceServer hbms = this; httpServer.getServerConfiguration().addHttpHandler(new HttpHandler() { private void sendGSON_to_web(OutputStream gos, Gson gson, Object obj) { try (PrintWriter pw = new PrintWriter(gos)) { pw.write(gson.toJson(obj)); pw.close(); } } @Override public void service(Request request, Response response) throws Exception { OutputStream gos = response.getOutputStream(); String uri = request.getRequestURI(); String path = uri.substring(uri.lastIndexOf("/") + 1).trim().toLowerCase(); Gson gson = (new GsonBuilder()).create(); String ip_address, hostname; HBox_Actions hba; Thread thread; Editor editor; switch (path) { case "list_drivers": String[] __paths = new String[0]; File driverFolder = new File(DefaultConfig.DRIVERS_FOLDER); if (driverFolder.exists()) { File[] paths = driverFolder.listFiles((File pathname) -> { String ext = pathname.getAbsolutePath(); ext = ext.substring(ext.lastIndexOf(".") + 1).trim().toLowerCase(); return ext.equals("kar"); }); __paths = new String[paths.length]; int k = 0; for (File _path : paths) { __paths[k] = _path.getName(); k++; } } sendGSON_to_web(gos, gson, __paths); break; case "reboot_hbox": hostname = request.getParameter("hostname"); ip_address = request.getParameter("ip_address"); if (hostname != null && ip_address != null) { hba = new HBox_Actions(ip_address, hostname, hbmws.getConns().toArray(new WebSocket[hbmws.getConns().size()]), new String[] { "hbox_reboot" }, threadGroup_LOG, hbms); thread = new Thread(hba); thread.start(); } break; case "start": String result1 = request.getParameter("result"); String[] drivers = null; if (request.getParameter("drivers") != null) { drivers = (String[]) gson.fromJson(request.getParameter("drivers"), String[].class); } HBox hb = (HBox) gson.fromJson(result1, HBox.class); hosts = hb.getHosts(); actions = hb.getActions(); for (Host host : hosts) { try { HBox_Actions hba1 = new HBox_Actions(host.getIp_address(), host.getHost_name(), hbmws.getConns().toArray(new WebSocket[hbmws.getConns().size()]), actions, threadGroup_LOG, hbms); if (drivers != null) { hba1.setDrivers(drivers); } thread = new Thread(hba1); thread.start(); } catch (Exception ex) { DCXLogger.error(HBoxMaintenanceServer.class, Level.SEVERE, ex); } } break; case "crontab": editor = new Editor(DefaultConfig.HBOX_CRONTAB, FileUtils.readFileToString(new File(DefaultConfig.HBOX_CRONTAB), "UTF-8")); sendGSON_to_web(gos, gson, editor); break; case "wpa_supplicant": editor = new Editor(DefaultConfig.HBOX_WIFI, FileUtils.readFileToString(new File(DefaultConfig.HBOX_WIFI), "UTF-8")); sendGSON_to_web(gos, gson, editor); break; case "apply_changes": String file = request.getParameter("file"); String content = request.getParameter("content"); if (file != null && content != null) { String[] contents; if (content.contains("\r\n")) { contents = content.split("\r\n"); } else if (content.contains("\n\r")) { contents = content.split("\n\r"); } else { contents = content.split("\r"); } if (file.equals("wpa_supplicant.conf") || file.equals("crontab")) { try (BufferedWriter bw = Files.newBufferedWriter( Paths.get(DefaultConfig.HBOX_FOLDER + File.separator + file), Charset.forName("UTF-8"), StandardOpenOption.TRUNCATE_EXISTING)) { for (String s : contents) { bw.write(s); bw.write("\n"); } bw.close(); } } } break; case "logout": request.getSession().removeAttribute("user-login"); try (PrintWriter pw = new PrintWriter(gos)) { pw.write("1"); } break; case "login": String username = request.getParameter("username"); String password = request.getParameter("password"); try (PrintWriter pw = new PrintWriter(gos)) { if (username != null && password != null) { if (saveLoginSession(request.getSession(), username, password)) { pw.write("1"); } else { pw.write("0"); } } else { pw.write("0"); } } break; default: gos.write(getContent(uri, response, request)); } } }); httpServer.start(); } catch (IOException ex) { DCXLogger.error(HBoxMaintenanceServer.class, Level.SEVERE, ex); } }