List of usage examples for java.nio.file StandardOpenOption CREATE_NEW
StandardOpenOption CREATE_NEW
To view the source code for java.nio.file StandardOpenOption CREATE_NEW.
Click Source Link
From source file:com.github.ansell.shp.SHPDump.java
public static void main(String... args) throws Exception { final OptionParser parser = new OptionParser(); final OptionSpec<Void> help = parser.accepts("help").forHelp(); final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required() .describedAs("The input SHP file"); final OptionSpec<File> output = parser.accepts("output").withRequiredArg().ofType(File.class).required() .describedAs("The output directory to use for debugging files"); final OptionSpec<String> outputPrefix = parser.accepts("prefix").withRequiredArg().ofType(String.class) .defaultsTo("shp-debug").describedAs("The output prefix to use for debugging files"); final OptionSpec<File> outputMappingTemplate = parser.accepts("output-mapping").withRequiredArg() .ofType(File.class).describedAs("The output mapping template file if it needs to be generated."); final OptionSpec<Integer> resolution = parser.accepts("resolution").withRequiredArg().ofType(Integer.class) .defaultsTo(2048).describedAs("The output image file resolution"); final OptionSpec<String> format = parser.accepts("format").withRequiredArg().ofType(String.class) .defaultsTo("png").describedAs("The output image format"); final OptionSpec<String> removeIfEmpty = parser.accepts("remove-if-empty").withRequiredArg() .ofType(String.class).describedAs( "The name of an attribute to remove if its value is empty before outputting the resulting shapefile. Use multiple times to specify multiple fields to check"); OptionSet options = null;//from w w w .j ava 2s . c o m try { options = parser.parse(args); } catch (final OptionException e) { System.out.println(e.getMessage()); parser.printHelpOn(System.out); throw e; } if (options.has(help)) { parser.printHelpOn(System.out); return; } final Path inputPath = input.value(options).toPath(); if (!Files.exists(inputPath)) { throw new FileNotFoundException("Could not find input SHP file: " + inputPath.toString()); } final Path outputPath = output.value(options).toPath(); if (!Files.exists(outputPath)) { throw new FileNotFoundException("Output directory does not exist: " + outputPath.toString()); } final Path outputMappingPath = options.has(outputMappingTemplate) ? outputMappingTemplate.value(options).toPath() : null; if (options.has(outputMappingTemplate) && Files.exists(outputMappingPath)) { throw new FileNotFoundException( "Output mapping template file already exists: " + outputMappingPath.toString()); } final Set<String> filterFields = ConcurrentHashMap.newKeySet(); if (options.has(removeIfEmpty)) { for (String nextFilterField : removeIfEmpty.values(options)) { System.out.println("Will filter field if empty value found: " + nextFilterField); filterFields.add(nextFilterField); } } if (!filterFields.isEmpty()) { System.out.println("Full set of filter fields: " + filterFields); } final String prefix = outputPrefix.value(options); FileDataStore store = FileDataStoreFinder.getDataStore(inputPath.toFile()); if (store == null) { throw new RuntimeException("Could not read the given input as an ESRI Shapefile: " + inputPath.toAbsolutePath().toString()); } for (String typeName : new LinkedHashSet<>(Arrays.asList(store.getTypeNames()))) { System.out.println(""); System.out.println("Type: " + typeName); SimpleFeatureSource featureSource = store.getFeatureSource(typeName); SimpleFeatureType schema = featureSource.getSchema(); Name outputSchemaName = new NameImpl(schema.getName().getNamespaceURI(), schema.getName().getLocalPart().replace(" ", "").replace("%20", "")); System.out.println("Replacing name on schema: " + schema.getName() + " with " + outputSchemaName); SimpleFeatureType outputSchema = SHPUtils.changeSchemaName(schema, outputSchemaName); List<String> attributeList = new ArrayList<>(); for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) { System.out.println("Attribute: " + attribute.getName().toString()); attributeList.add(attribute.getName().toString()); } CsvSchema csvSchema = CSVUtil.buildSchema(attributeList); SimpleFeatureCollection collection = featureSource.getFeatures(); int featureCount = 0; Path nextCSVFile = outputPath.resolve(prefix + ".csv"); Path nextSummaryCSVFile = outputPath .resolve(prefix + "-" + outputSchema.getTypeName() + "-Summary.csv"); List<SimpleFeature> outputFeatureList = new CopyOnWriteArrayList<>(); try (SimpleFeatureIterator iterator = collection.features(); Writer bufferedWriter = Files.newBufferedWriter(nextCSVFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); SequenceWriter csv = CSVUtil.newCSVWriter(bufferedWriter, csvSchema);) { List<String> nextLine = new ArrayList<>(); while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); featureCount++; if (featureCount <= 2) { System.out.println(""); System.out.println(feature.getIdentifier()); } else if (featureCount % 100 == 0) { System.out.print("."); } boolean filterThisFeature = false; for (AttributeDescriptor attribute : schema.getAttributeDescriptors()) { String featureString = Optional.ofNullable(feature.getAttribute(attribute.getName())) .orElse("").toString(); nextLine.add(featureString); if (filterFields.contains(attribute.getName().toString()) && featureString.trim().isEmpty()) { filterThisFeature = true; } if (featureString.length() > 100) { featureString = featureString.substring(0, 100) + "..."; } if (featureCount <= 2) { System.out.print(attribute.getName() + "="); System.out.println(featureString); } } if (!filterThisFeature) { outputFeatureList.add(SHPUtils.changeSchemaName(feature, outputSchema)); csv.write(nextLine); } nextLine.clear(); } } try (Reader csvReader = Files.newBufferedReader(nextCSVFile, StandardCharsets.UTF_8); Writer summaryOutput = Files.newBufferedWriter(nextSummaryCSVFile, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); final Writer mappingWriter = options.has(outputMappingTemplate) ? Files.newBufferedWriter(outputMappingPath) : NullWriter.NULL_WRITER) { CSVSummariser.runSummarise(csvReader, summaryOutput, mappingWriter, CSVSummariser.DEFAULT_SAMPLE_COUNT, false); } if (featureCount > 100) { System.out.println(""); } System.out.println(""); System.out.println("Feature count: " + featureCount); SimpleFeatureCollection outputCollection = new ListFeatureCollection(outputSchema, outputFeatureList); Path outputShapefilePath = outputPath.resolve(prefix + "-" + outputSchema.getTypeName() + "-dump"); if (!Files.exists(outputShapefilePath)) { Files.createDirectory(outputShapefilePath); } SHPUtils.writeShapefile(outputCollection, outputShapefilePath); // Create ZIP file from the contents to keep the subfiles together Path outputShapefileZipPath = outputPath .resolve(prefix + "-" + outputSchema.getTypeName() + "-dump.zip"); try (final OutputStream out = Files.newOutputStream(outputShapefileZipPath, StandardOpenOption.CREATE_NEW); final ZipOutputStream zip = new ZipOutputStream(out, StandardCharsets.UTF_8);) { Files.list(outputShapefilePath).forEachOrdered(Unchecked.consumer(e -> { zip.putNextEntry(new ZipEntry(e.getFileName().toString())); Files.copy(e, zip); zip.closeEntry(); })); } try (final OutputStream outputStream = Files.newOutputStream( outputPath.resolve(prefix + "." + format.value(options)), StandardOpenOption.CREATE_NEW);) { MapContent map = new MapContent(); map.setTitle(prefix + "-" + outputSchema.getTypeName()); Style style = SLD.createSimpleStyle(featureSource.getSchema()); Layer layer = new FeatureLayer(new CollectionFeatureSource(outputCollection), style); map.addLayer(layer); SHPUtils.renderImage(map, outputStream, resolution.value(options), format.value(options)); } } }
From source file:net.radai.confusion.spring.SpringAnnotationConfigTest.java
@Test public void testSpringAnnotationIntegration() throws Exception { Path dir = Files.createTempDirectory("test"); Path targetFile = dir.resolve("confFile"); try (InputStream is = getClass().getClassLoader().getResourceAsStream("cats.ini"); OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) { ByteStreams.copy(is, os);// www . j av a2s . c o m } String absolutePath = targetFile.toFile().getCanonicalPath(); System.setProperty("confFile", absolutePath); ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("annotationSpringContext.xml"); //noinspection unchecked SpringAwareConfigurationService<Cats> confService = (SpringAwareConfigurationService<Cats>) context .getBean(ConfigurationService.class); Jsr330AnnotatedConfigurationConsumerBean consumer = context .getBean(Jsr330AnnotatedConfigurationConsumerBean.class); //noinspection unchecked Assert.assertNotNull(consumer.getConfService()); Assert.assertNotNull(consumer.getInitialConf()); Assert.assertTrue(consumer.getCats().isEmpty()); try (InputStream is = getClass().getClassLoader().getResourceAsStream("cat.ini"); OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) { ByteStreams.copy(is, os); } Thread.sleep(100); //verify event was received Assert.assertEquals(1, consumer.getCats().size()); Assert.assertTrue(consumer.getInitialConf() != consumer.getCats().get(0)); Assert.assertTrue(confService.getConfiguration() == consumer.getCats().get(0)); context.close(); }
From source file:net.radai.confusion.spring.SpringXmlConfTest.java
@Test public void testSpringXmlIntegration() throws Exception { Path dir = Files.createTempDirectory("test"); Path targetFile = dir.resolve("confFile"); try (InputStream is = getClass().getClassLoader().getResourceAsStream("cats.ini"); OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) { ByteStreams.copy(is, os);/* w ww . j a v a 2s. c o m*/ } String absolutePath = targetFile.toFile().getCanonicalPath(); System.setProperty("confFile", absolutePath); ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("xmlSpringContext.xml"); //noinspection unchecked SpringAwareConfigurationService<Cats> confService = (SpringAwareConfigurationService<Cats>) context .getBean(ConfigurationService.class); TraditionalConfigurationConsumerBean consumer = context.getBean(TraditionalConfigurationConsumerBean.class); //noinspection unchecked SimpleConfigurationService<Cats> delegate = (SimpleConfigurationService<Cats>) ReflectionTestUtils .getField(confService, "delegate"); Assert.assertNotNull(confService.getConfiguration()); Assert.assertTrue(delegate.isStarted()); Assert.assertTrue(consumer.getConf() == confService.getConfiguration()); Assert.assertTrue(consumer.getConfService() == confService); Assert.assertTrue(consumer.getCats().isEmpty()); try (InputStream is = getClass().getClassLoader().getResourceAsStream("cat.ini"); OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) { ByteStreams.copy(is, os); } Thread.sleep(100); //verify event was received Assert.assertEquals(1, consumer.getCats().size()); Assert.assertTrue(consumer.getConf() != consumer.getCats().get(0)); Assert.assertTrue(confService.getConfiguration() == consumer.getCats().get(0)); context.close(); Assert.assertFalse(delegate.isStarted()); }
From source file:com.sastix.cms.server.utils.FileService.java
private String saveFile(String relativePath, byte[] resourceBinary) { Path path = Paths.get(volume + relativePath); try {//w w w .j a v a 2 s . c o m Files.write(path, resourceBinary, StandardOpenOption.CREATE_NEW); } catch (IOException e) { e.printStackTrace(); } return path.getFileName().toString(); }
From source file:net.minecrell.serverlistplus.canary.SnakeYAML.java
@SneakyThrows public static void load(Plugin plugin) { try { // Check if it is already loaded Class.forName("org.yaml.snakeyaml.Yaml"); return;//from w w w.j a v a 2 s . c o m } catch (ClassNotFoundException ignored) { } Path path = Paths.get("lib", SNAKE_YAML_JAR); if (Files.notExists(path)) { Files.createDirectories(path.getParent()); plugin.getLogman().info("Downloading SnakeYAML..."); URL url = new URL(SNAKE_YAML); MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); try (ReadableByteChannel source = Channels.newChannel(new DigestInputStream(url.openStream(), sha1)); FileChannel out = FileChannel.open(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { out.transferFrom(source, 0, Long.MAX_VALUE); } if (!new String(Hex.encodeHex(sha1.digest())).equals(EXPECTED_HASH)) { Files.delete(path); throw new IllegalStateException( "Downloaded SnakeYAML, but checksum check failed. Please try again later."); } plugin.getLogman().info("Successfully downloaded!"); } loadJAR(path); }
From source file:com.google.jenkins.plugins.persistentmaster.volume.zip.ZipCreator.java
ZipCreator(Path zip) throws IOException { zipPath = Preconditions.checkNotNull(zip); Preconditions.checkArgument(!Files.exists(zipPath), "zip file exists"); logger.finer("Creating zip volume for path: " + zipPath); zipStream = new ZipArchiveOutputStream(Files.newOutputStream(zipPath, StandardOpenOption.CREATE_NEW)); // unfortunately there is no typesafe way of doing this zipStream.setEncoding(UTF_8);/* w w w . j a v a 2 s . c om*/ zipStream.setUseZip64(Zip64Mode.AsNeeded); }
From source file:org.trustedanalytics.servicebroker.hive.config.ExternalConfiguration.java
public String getKeyTabLocation() throws IOException { String keyTabFilePath = String.format("%s/%s.keytab", keyTabsDir, PrincipalNameNormalizer.create().normalize(getHiveSuperUser())); LOGGER.info("Trying to write keytab file" + keyTabFilePath); Path path = Paths.get(keyTabFilePath); if (Files.notExists(path)) { Files.write(path, Base64.getDecoder().decode(getHiveSuperUserKeyTab()), StandardOpenOption.CREATE_NEW); } else if (Files.isDirectory(path)) { throw new IOException( String.format("Under path %s exists directory. It's path where hive superuser keytab " + "is stored. Please move or delete this directory", keyTabFilePath)); }/*from w w w. j av a 2 s.c o m*/ return keyTabFilePath; }
From source file:org.jhk.pulsing.web.aspect.UserDaoAspect.java
@AfterReturning(pointcut = "execution(org.jhk.pulsing.web.common.Result+ org.jhk.pulsing.web.dao.*.UserDao.*(..))", returning = "result") public void patchUser(JoinPoint joinPoint, Result<User> result) { if (result.getCode() != SUCCESS) { return;//from www . j a v a 2 s . c o m } User user = result.getData(); user.setPassword(""); //blank out password Picture picture = user.getPicture(); _LOGGER.debug("UserDaoAspect.setPictureUrl" + user); if (picture != null && picture.getName() != null) { ByteBuffer pBuffer = picture.getContent(); String path = applicationContext.getServletContext().getRealPath("/resources/img"); File parent = Paths.get(path).toFile(); if (!parent.exists()) { parent.mkdirs(); } String pFileName = user.getId().getId() + "_" + pBuffer.hashCode() + "_" + picture.getName(); File pFile = Paths.get(path, pFileName).toFile(); if (!pFile.exists()) { try (OutputStream fStream = Files.newOutputStream(pFile.toPath(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { fStream.write(pBuffer.array()); } catch (IOException iException) { iException.printStackTrace(); pFile = null; } } if (pFile != null) { _LOGGER.debug("UserDaoAspect Setting picture url - " + _RESOURCE_PREFIX + pFile.getName()); picture.setUrl(_RESOURCE_PREFIX + pFile.getName()); } } }
From source file:io.druid.query.groupby.epinephelinae.LimitedTemporaryStorage.java
/** * Create a new temporary file. All methods of the returned output stream may throw * {@link TemporaryStorageFullException} if the temporary storage area fills up. * * @return output stream to the file/*w ww .j av a2 s.c o m*/ * * @throws TemporaryStorageFullException if the temporary storage area is full * @throws IOException if something goes wrong while creating the file */ public LimitedOutputStream createFile() throws IOException { if (bytesUsed.get() >= maxBytesUsed) { throw new TemporaryStorageFullException(maxBytesUsed); } synchronized (files) { if (closed) { throw new ISE("Closed"); } FileUtils.forceMkdir(storageDirectory); final File theFile = new File(storageDirectory, StringUtils.format("%08d.tmp", files.size())); final EnumSet<StandardOpenOption> openOptions = EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE); final FileChannel channel = FileChannel.open(theFile.toPath(), openOptions); files.add(theFile); return new LimitedOutputStream(theFile, Channels.newOutputStream(channel)); } }
From source file:it.polimi.diceH2020.launcher.utility.FileUtility.java
public @NotNull File createTempZip(@NotNull Map<String, String> inputFiles) throws IOException { File folder = Files.createTempDirectory(settings.getWorkingDirectory().toPath(), null).toFile(); policy.markForDeletion(folder);//from w w w . j av a2 s. c om List<File> tempFiles = new LinkedList<>(); for (Map.Entry<String, String> entry : inputFiles.entrySet()) { File tmp = new File(folder, entry.getKey()); if (tmp.getParentFile().mkdirs() || tmp.getParentFile().isDirectory()) { tempFiles.add(tmp); Files.write(tmp.toPath(), Compressor.decompress(entry.getValue()).getBytes(), StandardOpenOption.CREATE_NEW); } else throw new IOException("could not prepare directory structure for ZIP file"); } String fileName = String.format("%s.zip", folder.getName()); File zip = new File(settings.getWorkingDirectory(), fileName); policy.markForDeletion(zip); zipFolder(folder, zip); tempFiles.forEach(policy::delete); policy.delete(folder); return zip; }