List of usage examples for java.nio.file StandardCopyOption REPLACE_EXISTING
StandardCopyOption REPLACE_EXISTING
To view the source code for java.nio.file StandardCopyOption REPLACE_EXISTING.
Click Source Link
From source file:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java
public List<DataFile> createDataFiles(DatasetVersion version, InputStream inputStream, String fileName, String suppliedContentType) throws IOException { List<DataFile> datafiles = new ArrayList<DataFile>(); String warningMessage = null; // save the file, in the temporary location for now: Path tempFile = null;//from ww w.j a v a 2 s . com if (getFilesTempDirectory() != null) { tempFile = Files.createTempFile(Paths.get(getFilesTempDirectory()), "tmp", "upload"); // "temporary" location is the key here; this is why we are not using // the DataStore framework for this - the assumption is that // temp files will always be stored on the local filesystem. // -- L.A. Jul. 2014 logger.fine("Will attempt to save the file as: " + tempFile.toString()); Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING); } else { throw new IOException("Temp directory is not configured."); } logger.fine("mime type supplied: " + suppliedContentType); // Let's try our own utilities (Jhove, etc.) to determine the file type // of the uploaded file. (We may already have a mime type supplied for this // file - maybe the type that the browser recognized on upload; or, if // it's a harvest, maybe the remote server has already given us the type // for this file... with our own type utility we may or may not do better // than the type supplied: // -- L.A. String recognizedType = null; String finalType = null; try { recognizedType = FileUtil.determineFileType(tempFile.toFile(), fileName); logger.fine("File utility recognized the file as " + recognizedType); if (recognizedType != null && !recognizedType.equals("")) { // is it any better than the type that was supplied to us, // if any? // This is not as trivial a task as one might expect... // We may need a list of "good" mime types, that should always // be chosen over other choices available. Maybe it should // even be a weighed list... as in, "application/foo" should // be chosen over "application/foo-with-bells-and-whistles". // For now the logic will be as follows: // // 1. If the contentType supplied (by the browser, most likely) // is some form of "unknown", we always discard it in favor of // whatever our own utilities have determined; // 2. We should NEVER trust the browser when it comes to the // following "ingestable" types: Stata, SPSS, R; // 2a. We are willing to TRUST the browser when it comes to // the CSV and XSLX ingestable types. // 3. We should ALWAYS trust our utilities when it comes to // ingestable types. if (suppliedContentType == null || suppliedContentType.equals("") || suppliedContentType.equalsIgnoreCase(MIME_TYPE_UNDETERMINED_DEFAULT) || suppliedContentType.equalsIgnoreCase(MIME_TYPE_UNDETERMINED_BINARY) || (ingestableAsTabular(suppliedContentType) && !suppliedContentType.equalsIgnoreCase(MIME_TYPE_CSV) && !suppliedContentType.equalsIgnoreCase(MIME_TYPE_CSV_ALT) && !suppliedContentType.equalsIgnoreCase(MIME_TYPE_XLSX)) || ingestableAsTabular(recognizedType) || recognizedType.equals("application/fits-gzipped") || recognizedType.equalsIgnoreCase(ShapefileHandler.SHAPEFILE_FILE_TYPE) || recognizedType.equals(MIME_TYPE_ZIP)) { finalType = recognizedType; } } } catch (Exception ex) { logger.warning("Failed to run the file utility mime type check on file " + fileName); } if (finalType == null) { finalType = (suppliedContentType == null || suppliedContentType.equals("")) ? MIME_TYPE_UNDETERMINED_DEFAULT : suppliedContentType; } // A few special cases: // if this is a gzipped FITS file, we'll uncompress it, and ingest it as // a regular FITS file: if (finalType.equals("application/fits-gzipped")) { InputStream uncompressedIn = null; String finalFileName = fileName; // if the file name had the ".gz" extension, remove it, // since we are going to uncompress it: if (fileName != null && fileName.matches(".*\\.gz$")) { finalFileName = fileName.replaceAll("\\.gz$", ""); } DataFile datafile = null; try { uncompressedIn = new GZIPInputStream(new FileInputStream(tempFile.toFile())); datafile = createSingleDataFile(version, uncompressedIn, finalFileName, MIME_TYPE_UNDETERMINED_DEFAULT); } catch (IOException ioex) { datafile = null; } finally { if (uncompressedIn != null) { try { uncompressedIn.close(); } catch (IOException e) { } } } // If we were able to produce an uncompressed file, we'll use it // to create and return a final DataFile; if not, we're not going // to do anything - and then a new DataFile will be created further // down, from the original, uncompressed file. if (datafile != null) { // remove the compressed temp file: try { tempFile.toFile().delete(); } catch (SecurityException ex) { // (this is very non-fatal) logger.warning("Failed to delete temporary file " + tempFile.toString()); } datafiles.add(datafile); return datafiles; } // If it's a ZIP file, we are going to unpack it and create multiple // DataFile objects from its contents: } else if (finalType.equals("application/zip")) { ZipInputStream unZippedIn = null; ZipEntry zipEntry = null; int fileNumberLimit = systemConfig.getZipUploadFilesLimit(); try { Charset charset = null; /* TODO: (?) We may want to investigate somehow letting the user specify the charset for the filenames in the zip file... - otherwise, ZipInputStream bails out if it encounteres a file name that's not valid in the current charest (i.e., UTF-8, in our case). It would be a bit trickier than what we're doing for SPSS tabular ingests - with the lang. encoding pulldown menu - because this encoding needs to be specified *before* we upload and attempt to unzip the file. -- L.A. 4.0 beta12 logger.info("default charset is "+Charset.defaultCharset().name()); if (Charset.isSupported("US-ASCII")) { logger.info("charset US-ASCII is supported."); charset = Charset.forName("US-ASCII"); if (charset != null) { logger.info("was able to obtain charset for US-ASCII"); } } */ if (charset != null) { unZippedIn = new ZipInputStream(new FileInputStream(tempFile.toFile()), charset); } else { unZippedIn = new ZipInputStream(new FileInputStream(tempFile.toFile())); } while (true) { try { zipEntry = unZippedIn.getNextEntry(); } catch (IllegalArgumentException iaex) { // Note: // ZipInputStream documentation doesn't even mention that // getNextEntry() throws an IllegalArgumentException! // but that's what happens if the file name of the next // entry is not valid in the current CharSet. // -- L.A. warningMessage = "Failed to unpack Zip file. (Unknown Character Set used in a file name?) Saving the file as is."; logger.warning(warningMessage); throw new IOException(); } if (zipEntry == null) { break; } // Note that some zip entries may be directories - we // simply skip them: if (!zipEntry.isDirectory()) { if (datafiles.size() > fileNumberLimit) { logger.warning("Zip upload - too many files."); warningMessage = "The number of files in the zip archive is over the limit (" + fileNumberLimit + "); please upload a zip archive with fewer files, if you want them to be ingested " + "as individual DataFiles."; throw new IOException(); } String fileEntryName = zipEntry.getName(); logger.fine("ZipEntry, file: " + fileEntryName); if (fileEntryName != null && !fileEntryName.equals("")) { String shortName = fileEntryName.replaceFirst("^.*[\\/]", ""); // Check if it's a "fake" file - a zip archive entry // created for a MacOS X filesystem element: (these // start with "._") if (!shortName.startsWith("._") && !shortName.startsWith(".DS_Store") && !"".equals(shortName)) { // OK, this seems like an OK file entry - we'll try // to read it and create a DataFile with it: DataFile datafile = createSingleDataFile(version, unZippedIn, shortName, MIME_TYPE_UNDETERMINED_DEFAULT, false); if (!fileEntryName.equals(shortName)) { String categoryName = fileEntryName.replaceFirst("[\\/][^\\/]*$", ""); if (!"".equals(categoryName)) { logger.fine("setting category to " + categoryName); //datafile.getFileMetadata().setCategory(categoryName.replaceAll("[\\/]", "-")); datafile.getFileMetadata() .addCategoryByName(categoryName.replaceAll("[\\/]", "-")); } } if (datafile != null) { // We have created this datafile with the mime type "unknown"; // Now that we have it saved in a temporary location, // let's try and determine its real type: String tempFileName = getFilesTempDirectory() + "/" + datafile.getStorageIdentifier(); try { recognizedType = FileUtil.determineFileType(new File(tempFileName), shortName); logger.fine("File utility recognized unzipped file as " + recognizedType); if (recognizedType != null && !recognizedType.equals("")) { datafile.setContentType(recognizedType); } } catch (Exception ex) { logger.warning("Failed to run the file utility mime type check on file " + fileName); } datafiles.add(datafile); } } } } unZippedIn.closeEntry(); } } catch (IOException ioex) { // just clear the datafiles list and let // ingest default to creating a single DataFile out // of the unzipped file. logger.warning("Unzipping failed; rolling back to saving the file as is."); if (warningMessage == null) { warningMessage = "Failed to unzip the file. Saving the file as is."; } datafiles.clear(); } finally { if (unZippedIn != null) { try { unZippedIn.close(); } catch (Exception zEx) { } } } if (datafiles.size() > 0) { // link the data files to the dataset/version: Iterator<DataFile> itf = datafiles.iterator(); while (itf.hasNext()) { DataFile datafile = itf.next(); datafile.setOwner(version.getDataset()); if (version.getFileMetadatas() == null) { version.setFileMetadatas(new ArrayList()); } version.getFileMetadatas().add(datafile.getFileMetadata()); datafile.getFileMetadata().setDatasetVersion(version); /* TODO!! // re-implement this in some way that does not use the // deprecated .getCategory() on FileMeatadata: if (datafile.getFileMetadata().getCategory() != null) { datafile.getFileMetadata().addCategoryByName(datafile.getFileMetadata().getCategory()); datafile.getFileMetadata().setCategory(null); -- done? see above? } */ version.getDataset().getFiles().add(datafile); } // remove the uploaded zip file: try { Files.delete(tempFile); } catch (IOException ioex) { // do nothing - it's just a temp file. logger.warning("Could not remove temp file " + tempFile.getFileName().toString()); } // and return: return datafiles; } } else if (finalType.equalsIgnoreCase(ShapefileHandler.SHAPEFILE_FILE_TYPE)) { // Shape files may have to be split into multiple files, // one zip archive per each complete set of shape files: //File rezipFolder = new File(this.getFilesTempDirectory()); File rezipFolder = this.getShapefileUnzipTempDirectory(); IngestServiceShapefileHelper shpIngestHelper; shpIngestHelper = new IngestServiceShapefileHelper(tempFile.toFile(), rezipFolder); boolean didProcessWork = shpIngestHelper.processFile(); if (!(didProcessWork)) { logger.severe("Processing of zipped shapefile failed."); return null; } for (File finalFile : shpIngestHelper.getFinalRezippedFiles()) { FileInputStream finalFileInputStream = new FileInputStream(finalFile); finalType = this.getContentType(finalFile); if (finalType == null) { logger.warning("Content type is null; but should default to 'MIME_TYPE_UNDETERMINED_DEFAULT'"); continue; } DataFile new_datafile = createSingleDataFile(version, finalFileInputStream, finalFile.getName(), finalType); if (new_datafile != null) { datafiles.add(new_datafile); } else { logger.severe("Could not add part of rezipped shapefile. new_datafile was null: " + finalFile.getName()); } finalFileInputStream.close(); } // Delete the temp directory used for unzipping /* logger.fine("Delete temp shapefile unzip directory: " + rezipFolder.getAbsolutePath()); FileUtils.deleteDirectory(rezipFolder); // Delete rezipped files for (File finalFile : shpIngestHelper.getFinalRezippedFiles()){ if (finalFile.isFile()){ finalFile.delete(); } } */ if (datafiles.size() > 0) { return datafiles; } else { logger.severe("No files added from directory of rezipped shapefiles"); } return null; } // Finally, if none of the special cases above were applicable (or // if we were unable to unpack an uploaded file, etc.), we'll just // create and return a single DataFile: // (Note that we are passing null for the InputStream; that's because // we already have the file saved; we'll just need to rename it, below) DataFile datafile = createSingleDataFile(version, null, fileName, finalType); if (datafile != null) { fileService.generateStorageIdentifier(datafile); if (!tempFile.toFile() .renameTo(new File(getFilesTempDirectory() + "/" + datafile.getStorageIdentifier()))) { return null; } // MD5: MD5Checksum md5Checksum = new MD5Checksum(); try { datafile.setmd5( md5Checksum.CalculateMD5(getFilesTempDirectory() + "/" + datafile.getStorageIdentifier())); } catch (Exception md5ex) { logger.warning("Could not calculate MD5 signature for new file " + fileName); } if (warningMessage != null) { createIngestFailureReport(datafile, warningMessage); datafile.SetIngestProblem(); } datafiles.add(datafile); return datafiles; } return null; }
From source file:net.redstoneore.legacyfactions.Factions.java
private void migrations() throws IOException { // Move all database files in database folder if (!Files.exists(FactionsJSON.getDatabasePath())) { Files.createDirectories(FactionsJSON.getDatabasePath()); }/*from w w w . j a va 2 s.c o m*/ Path oldBoardJson = this.getPluginFolder().resolve("board.json"); Path oldFactionsJson = this.getPluginFolder().resolve("factions.json"); Path oldPlayersJson = this.getPluginFolder().resolve("players.json"); if (Files.exists(oldBoardJson)) { if (Files.exists(JSONBoard.getJsonFile())) { Files.move(JSONBoard.getJsonFile(), Paths.get(JSONBoard.getJsonFile().toString() + ".backup")); Factions.get().log("Moving 'database/board.json' -> 'database/board.json.backup'"); } Files.move(oldBoardJson, JSONBoard.getJsonFile()); Factions.get().log("Moving 'board.json' -> 'database/board.json'"); } if (Files.exists(oldFactionsJson)) { if (Files.exists(JSONFactionColl.getJsonFile())) { Files.move(JSONFactionColl.getJsonFile(), Paths.get(JSONFactionColl.getJsonFile().toString() + ".backup")); Factions.get().log("Moving 'database/factions.json' -> 'database/factions.json.backup'"); } Files.move(oldFactionsJson, JSONFactionColl.getJsonFile()); Factions.get().log("Moving 'factions.json' -> 'database/factions.json'"); } if (Files.exists(oldPlayersJson)) { if (Files.exists(JSONFPlayerColl.getJsonFile())) { Files.move(JSONFPlayerColl.getJsonFile(), Paths.get(JSONFPlayerColl.getJsonFile().toString() + ".backup")); Factions.get().log("Moving 'database/players.json' -> 'database/players.json.backup'"); } Files.move(oldPlayersJson, JSONFPlayerColl.getJsonFile()); Factions.get().log("Moving 'players.json' -> 'database/players.json'"); } // using new .js format Path oldConfJson = this.getPluginFolder().resolve("conf.json"); Path oldCommandAliasesJson = this.getPluginFolder().resolve("commandAliases.json"); Path oldTagsJson = this.getPluginFolder().resolve("tags.json"); Path newConfigJs = this.getPluginFolder().resolve("config.js"); Path newCommandAliasesJs = this.getPluginFolder().resolve("commandAliases.js"); Path newTagsJs = this.getPluginFolder().resolve("tags.js"); if (Files.exists(oldConfJson)) { if (Files.exists(newConfigJs)) { Files.move(newConfigJs, Paths.get(newConfigJs.toString() + ".backup"), StandardCopyOption.REPLACE_EXISTING); Factions.get().log("Moving 'config.js' -> 'config.js.backup'"); } Files.move(oldConfJson, newConfigJs, StandardCopyOption.REPLACE_EXISTING); Factions.get().log("Moving 'config.json' -> 'config.js'"); } if (Files.exists(oldCommandAliasesJson)) { if (Files.exists(newCommandAliasesJs)) { Files.move(newCommandAliasesJs, Paths.get(newCommandAliasesJs.toString() + ".backup"), StandardCopyOption.REPLACE_EXISTING); Factions.get().log("Moving 'commandAliases.js' -> 'commandAliases.js.backup'"); } Files.move(oldCommandAliasesJson, newCommandAliasesJs, StandardCopyOption.REPLACE_EXISTING); Factions.get().log("Moving 'commandAliases.json' -> 'commandAliases.js'"); } if (Files.exists(oldTagsJson)) { if (Files.exists(newTagsJs)) { Files.move(newTagsJs, Paths.get(newTagsJs.toString() + ".backup"), StandardCopyOption.REPLACE_EXISTING); Factions.get().log("Moving 'tags.js' -> 'tags.js.backup'"); } Files.move(oldTagsJson, newTagsJs, StandardCopyOption.REPLACE_EXISTING); Factions.get().log("Moving 'tags.json' -> 'tags.js'"); } // Move lang.yml to locale.yml Path localeOld = this.getPluginFolder().resolve("lang.yml"); Path localeNew = this.getPluginFolder().resolve("locale.yml"); if (Files.exists(localeOld)) { if (Files.exists(localeNew)) { Files.move(localeNew, Paths.get(localeNew.toString() + ".backup"), StandardCopyOption.REPLACE_EXISTING); Factions.get().log("Moving 'locale.yml' -> 'locale.yml.backup'"); } Files.move(localeOld, localeNew, StandardCopyOption.REPLACE_EXISTING); Factions.get().log("Moving 'lang.yml' -> 'locale.yml'"); } }
From source file:at.alladin.rmbt.statisticServer.export.ExportResource.java
@Get public Representation request(final String entity) { //Before doing anything => check if a cached file already exists and is new enough String property = System.getProperty("java.io.tmpdir"); final String filename_zip; final String filename_csv; //allow filtering by month/year int year = -1; int month = -1; int hours = -1; boolean hoursExport = false; boolean dateExport = false; if (getRequest().getAttributes().containsKey("hours")) { // export by hours try {//from w ww .jav a 2 s . c om hours = Integer.parseInt(getRequest().getAttributes().get("hours").toString()); } catch (NumberFormatException ex) { //Nothing -> just fall back } if (hours <= 7 * 24 && hours >= 1) { //limit to 1 week (avoid DoS) hoursExport = true; } } else if (!hoursExport && getRequest().getAttributes().containsKey("year")) { // export by month/year try { year = Integer.parseInt(getRequest().getAttributes().get("year").toString()); month = Integer.parseInt(getRequest().getAttributes().get("month").toString()); } catch (NumberFormatException ex) { //Nothing -> just fall back } if (year < 2099 && month > 0 && month <= 12 && year > 2000) { dateExport = true; } } if (hoursExport) { filename_zip = FILENAME_ZIP_HOURS.replace("%HOURS%", String.format("%03d", hours)); filename_csv = FILENAME_CSV_HOURS.replace("%HOURS%", String.format("%03d", hours)); cacheThresholdMs = 5 * 60 * 1000; //5 minutes } else if (dateExport) { filename_zip = FILENAME_ZIP.replace("%YEAR%", Integer.toString(year)).replace("%MONTH%", String.format("%02d", month)); filename_csv = FILENAME_CSV.replace("%YEAR%", Integer.toString(year)).replace("%MONTH%", String.format("%02d", month)); cacheThresholdMs = 23 * 60 * 60 * 1000; //23 hours } else { filename_zip = FILENAME_ZIP_CURRENT; filename_csv = FILENAME_CSV_CURRENT; cacheThresholdMs = 3 * 60 * 60 * 1000; //3 hours } final File cachedFile = new File(property + File.separator + ((zip) ? filename_zip : filename_csv)); final File generatingFile = new File( property + File.separator + ((zip) ? filename_zip : filename_csv) + "_tmp"); if (cachedFile.exists()) { //check if file has been recently created OR a file is currently being created if (((cachedFile.lastModified() + cacheThresholdMs) > (new Date()).getTime()) || (generatingFile.exists() && (generatingFile.lastModified() + cacheThresholdMs) > (new Date()).getTime())) { //if so, return the cached file instead of a cost-intensive new one final OutputRepresentation result = new OutputRepresentation( zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_CSV) { @Override public void write(OutputStream out) throws IOException { InputStream is = new FileInputStream(cachedFile); IOUtils.copy(is, out); out.close(); } }; if (zip) { final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(filename_zip); result.setDisposition(disposition); } return result; } } final String timeClause; if (dateExport) timeClause = " AND (EXTRACT (month FROM t.time AT TIME ZONE 'UTC') = " + month + ") AND (EXTRACT (year FROM t.time AT TIME ZONE 'UTC') = " + year + ") "; else if (hoursExport) timeClause = " AND time > now() - interval '" + hours + " hours' "; else timeClause = " AND time > current_date - interval '31 days' "; final String sql = "SELECT" + " ('P' || t.open_uuid) open_uuid," + " ('O' || t.open_test_uuid) open_test_uuid," + " to_char(t.time AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS') time_utc," + " nt.group_name cat_technology," + " nt.name network_type," + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') THEN" + " t.geo_lat" + " WHEN (t.geo_accuracy < ?) THEN" + " ROUND(t.geo_lat*1111)/1111" + " ELSE null" + " END) lat," + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') THEN" + " t.geo_long" + " WHEN (t.geo_accuracy < ?) THEN" + " ROUND(t.geo_long*741)/741 " + " ELSE null" + " END) long," + " (CASE WHEN ((t.geo_provider = 'manual') OR (t.geo_provider = 'geocoder')) THEN" + " 'rastered'" + //make raster transparent " ELSE t.geo_provider" + " END) loc_src," + " (CASE WHEN (t.geo_accuracy < ?) AND (t.geo_provider != 'manual') AND (t.geo_provider != 'geocoder') " + " THEN round(t.geo_accuracy::float * 10)/10 " + " WHEN (t.geo_accuracy < 100) AND ((t.geo_provider = 'manual') OR (t.geo_provider = 'geocoder')) THEN 100" + // limit accuracy to 100m " WHEN (t.geo_accuracy < ?) THEN round(t.geo_accuracy::float * 10)/10" + " ELSE null END) loc_accuracy, " + " (CASE WHEN (t.zip_code < 1000 OR t.zip_code > 9999) THEN null ELSE t.zip_code END) zip_code," + " t.gkz gkz," + " t.country_location country_location," + " t.speed_download download_kbit," + " t.speed_upload upload_kbit," + " round(t.ping_median::float / 100000)/10 ping_ms," + " t.lte_rsrp," + " t.lte_rsrq," + " ts.name server_name," + " duration test_duration," + " num_threads," + " t.plattform platform," + " COALESCE(adm.fullname, t.model) model," + " client_software_version client_version," + " network_operator network_mcc_mnc," + " network_operator_name network_name," + " network_sim_operator sim_mcc_mnc," + " nat_type," + " public_ip_asn asn," + " client_public_ip_anonymized ip_anonym," + " (ndt.s2cspd*1000)::int ndt_download_kbit," + " (ndt.c2sspd*1000)::int ndt_upload_kbit," + " COALESCE(t.implausible, false) implausible," + " t.signal_strength" + " FROM test t" + " LEFT JOIN network_type nt ON nt.uid=t.network_type" + " LEFT JOIN device_map adm ON adm.codename=t.model" + " LEFT JOIN test_server ts ON ts.uid=t.server_id" + " LEFT JOIN test_ndt ndt ON t.uid=ndt.test_id" + " WHERE " + " t.deleted = false" + timeClause + " AND status = 'FINISHED'" + " ORDER BY t.uid"; final String[] columns; final List<String[]> data = new ArrayList<>(); PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.prepareStatement(sql); //insert filter for accuracy double accuracy = Double.parseDouble(settings.getString("RMBT_GEO_ACCURACY_DETAIL_LIMIT")); ps.setDouble(1, accuracy); ps.setDouble(2, accuracy); ps.setDouble(3, accuracy); ps.setDouble(4, accuracy); ps.setDouble(5, accuracy); ps.setDouble(6, accuracy); if (!ps.execute()) return null; rs = ps.getResultSet(); final ResultSetMetaData meta = rs.getMetaData(); final int colCnt = meta.getColumnCount(); columns = new String[colCnt]; for (int i = 0; i < colCnt; i++) columns[i] = meta.getColumnName(i + 1); while (rs.next()) { final String[] line = new String[colCnt]; for (int i = 0; i < colCnt; i++) { final Object obj = rs.getObject(i + 1); line[i] = obj == null ? null : obj.toString(); } data.add(line); } } catch (final SQLException e) { e.printStackTrace(); return null; } finally { try { if (rs != null) rs.close(); if (ps != null) ps.close(); } catch (final SQLException e) { e.printStackTrace(); } } final OutputRepresentation result = new OutputRepresentation( zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_CSV) { @Override public void write(OutputStream out) throws IOException { //cache in file => create temporary temporary file (to // handle errors while fulfilling a request) String property = System.getProperty("java.io.tmpdir"); final File cachedFile = new File( property + File.separator + ((zip) ? filename_zip : filename_csv) + "_tmp"); OutputStream outf = new FileOutputStream(cachedFile); if (zip) { final ZipOutputStream zos = new ZipOutputStream(outf); final ZipEntry zeLicense = new ZipEntry("LIZENZ.txt"); zos.putNextEntry(zeLicense); final InputStream licenseIS = getClass().getResourceAsStream("DATA_LICENSE.txt"); IOUtils.copy(licenseIS, zos); licenseIS.close(); final ZipEntry zeCsv = new ZipEntry(filename_csv); zos.putNextEntry(zeCsv); outf = zos; } final OutputStreamWriter osw = new OutputStreamWriter(outf); final CSVPrinter csvPrinter = new CSVPrinter(osw, csvFormat); for (final String c : columns) csvPrinter.print(c); csvPrinter.println(); for (final String[] line : data) { for (final String f : line) csvPrinter.print(f); csvPrinter.println(); } csvPrinter.flush(); if (zip) outf.close(); //if we reach this code, the data is now cached in a temporary tmp-file //so, rename the file for "production use2 //concurrency issues should be solved by the operating system File newCacheFile = new File(property + File.separator + ((zip) ? filename_zip : filename_csv)); Files.move(cachedFile.toPath(), newCacheFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); FileInputStream fis = new FileInputStream(newCacheFile); IOUtils.copy(fis, out); fis.close(); out.close(); } }; if (zip) { final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(filename_zip); result.setDisposition(disposition); } return result; }
From source file:org.matonto.etl.rest.impl.DelimitedRestImpl.java
/** * Saves the contents of the InputStream to the specified path. * * @param fileInputStream a file in an InputStream * @param filePath the location to upload the file to *//*from ww w . j a v a 2s.c om*/ private void saveStreamToFile(InputStream fileInputStream, Path filePath) { try { Files.copy(fileInputStream, filePath, StandardCopyOption.REPLACE_EXISTING); fileInputStream.close(); } catch (FileNotFoundException e) { throw ErrorUtils.sendError(e, "Error writing delimited file", Response.Status.BAD_REQUEST); } catch (IOException e) { throw ErrorUtils.sendError(e, "Error parsing delimited file", Response.Status.BAD_REQUEST); } logger.info("File Uploaded: " + filePath); }
From source file:org.craftercms.studio.impl.v1.repository.disk.DiskContentRepository.java
/** * revert a version (create a new version based on an old version) * @param path - the path of the item to "revert" * @param version - old version ID to base to version on */// w w w. ja v a 2 s . co m public boolean revertContent(String path, String label, boolean major, String comment) { boolean success = false; synchronized (path) { String versionId = determineNextVersionLabel(path, major); InputStream versionContent = null; InputStream wipContent = null; try { versionContent = getVersionedContent(path, label); String versionPath = path + "--" + versionId; CopyOption options[] = { StandardCopyOption.REPLACE_EXISTING }; String pathToContent = versionPath.substring(0, versionPath.lastIndexOf(File.separator)); Files.createDirectories(constructVersionRepoPath(pathToContent)); Files.copy(versionContent, constructVersionRepoPath(versionPath), options); // write the repo content wipContent = getVersionedContent(path, label); Files.copy(wipContent, constructRepoPath(path), options); } catch (Exception err) { logger.error("error versioning file: " + path, err); versionId = null; } finally { closeInputStreamQuietly(versionContent); closeInputStreamQuietly(wipContent); } } return success; }
From source file:org.openstreetmap.josm.tools.Utils.java
/** * Simple file copy function that will overwrite the target file. * @param in The source file//from w ww . j ava 2s . co m * @param out The destination file * @return the path to the target file * @throws IOException if any I/O error occurs * @throws IllegalArgumentException if {@code in} or {@code out} is {@code null} * @since 7003 */ public static Path copyFile(File in, File out) throws IOException { CheckParameterUtil.ensureParameterNotNull(in, "in"); CheckParameterUtil.ensureParameterNotNull(out, "out"); return Files.copy(in.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING); }
From source file:pl.baczkowicz.spy.ui.configuration.BaseConfigurationManager.java
public static boolean createDefaultConfigFromFile(final File orig) { try {//from w w w.j a v a 2s .c om final File dest = BaseConfigurationManager.getDefaultConfigurationFileObject(); dest.mkdirs(); Files.copy(orig.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING); return true; } catch (IOException e) { // TODO: show warning dialog for invalid logger.error("Cannot copy configuration file", e); } return false; }
From source file:dotaSoundEditor.Controls.ItemPanel.java
@Override protected File promptUserForNewFile(String wavePath) { DefaultMutableTreeNode selectedTreeNode = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath); String waveString = selectedTreeNode.getUserObject().toString(); String allowedExtension = FilenameUtils.getExtension(waveString).replace("\"", ""); JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory())); FileNameExtensionFilter filter = allowedExtension.equals("wav") ? new FileNameExtensionFilter("WAVs", "wav") : new FileNameExtensionFilter("MP3s", "mp3"); chooser.setAcceptAllFileFilterUsed((false)); chooser.setFileFilter(filter);/* w w w. ja va 2s . c o m*/ chooser.setMultiSelectionEnabled(false); int chooserRetVal = chooser.showOpenDialog(chooser); if (chooserRetVal == JFileChooser.APPROVE_OPTION) { Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath()); int startIndex = -1; int endIndex = -1; //Get the actual value for the wavestring key-value pair. if (waveString.contains("\"wave\"")) { startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 2); endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 3); } else //Some wavestrings don't have the "wave" at the beginning for some reason { startIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 0); endIndex = Utility.nthOccurrence(selectedTreeNode.getUserObject().toString(), '\"', 1); } String waveStringFilePath = waveString.substring(startIndex, endIndex + 1); String waveStringNormalizedFilePath = waveStringFilePath.substring(0, waveStringFilePath.lastIndexOf("\"")); waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace(")", ""); waveStringNormalizedFilePath = waveStringNormalizedFilePath.replace("\"", ""); Path destPath = Paths.get(installDir, "/dota/sound/" + waveStringNormalizedFilePath); UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString()); try { new File(destPath.toString()).mkdirs(); Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING); if (waveString.contains("//")) { waveString = waveString .replace(waveString.substring(waveString.indexOf("//"), waveString.length()), ""); } waveString = waveString.replace(waveStringFilePath, "\"" + waveStringNormalizedFilePath + "\" //Replaced by: " + chosenFile.getFileName().toString()); selectedTreeNode.setUserObject(waveString); //Write out modified tree to scriptfile. ScriptParser parser = new ScriptParser(this.currentTreeModel); String scriptString = getCurrentScriptString(); Path scriptPath = Paths.get(scriptString); parser.writeModelToFile(scriptPath.toString()); //Update UI ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(waveString); ((DefaultTreeModel) currentTree.getModel()) .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()); JOptionPane.showMessageDialog(this, "Sound file successfully replaced."); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Unable to replace sound.\nDetails: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } return null; }
From source file:com.aol.advertising.qiao.injector.file.watcher.QiaoFileManager.java
private Path renameFile(Path src, Path target) throws IOException { if (!target.equals(src)) { logger.info("Rename file from " + src + " to " + target); Files.move(src, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }//from w w w . j av a 2 s . c om return target; }