List of usage examples for java.nio.file FileSystems getDefault
public static FileSystem getDefault()
From source file:com.acmutv.ontoqa.core.knowledge.KnowledgeManager.java
/** * Reads an ontology from a resource.//from w w w . j a va 2s . c o m * @param resource the resource to read. * @param prefix the default prefix for the ontology. * @param format the ontology format. * @return the ontology. * @throws IOException when ontology cannot be read. */ public static Ontology read(String resource, String prefix, OntologyFormat format) throws IOException { LOGGER.trace("resource={} prefix={} format={}", resource, prefix, format); Ontology ontology = new SimpleOntology(); Path path = FileSystems.getDefault().getPath(resource).toAbsolutePath(); try (InputStream in = Files.newInputStream(path)) { Model model = Rio.parse(in, prefix, format.getFormat()); ontology.merge(model); } return ontology; }
From source file:com.ccserver.digital.controller.CreditCardApplicationDocumentControllerTest.java
@Test public void save() throws IOException { File ifile = new File("./src/main/resources/sample"); Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf"); byte[] idDocByteArray = Files.readAllBytes(idDocPath); MockMultipartFile idDocMultipartFile = new MockMultipartFile("IdDoc", "IdDoc.pdf", "application/pdf", idDocByteArray);// www. j a va 2 s . c o m ResponseEntity<?> fileUploadResponse = mockDocController.saveAll( new MockMultipartFile[] { idDocMultipartFile }, new String[] { "front" }, Long.valueOf(1), Long.valueOf(1), request); Assert.assertNotNull(fileUploadResponse); }
From source file:org.dataconservancy.packaging.gui.presenter.impl.OpenExistingPackagePresenterImpl.java
public OpenExistingPackagePresenterImpl(OpenExistingPackageView view) { super(view);/*from ww w.jav a 2s . co m*/ this.view = view; this.directoryChooser = new DirectoryChooser(); this.fileChooser = new FileChooser(); view.setPresenter(this); bind(); // Staging directory is working directory by default. stagingDir = new File(System.getProperty("user.dir")); //If we can't write to the current working directory switch to the java temp dir which we should have write access to if (!Files.isWritable(FileSystems.getDefault().getPath(stagingDir.getPath()))) { stagingDir = new File(System.getProperty("java.io.tmpdir")); } }
From source file:org.apache.hadoop.hive.ql.MetaStoreDumpUtility.java
public static void setupMetaStoreTableColumnStatsFor30TBTPCDSWorkload(HiveConf conf, String tmpBaseDir) { Connection conn = null;/*from ww w. ja va 2s. c om*/ try { Properties props = new Properties(); // connection properties props.put("user", conf.get("javax.jdo.option.ConnectionUserName")); props.put("password", conf.get("javax.jdo.option.ConnectionPassword")); String url = conf.get("javax.jdo.option.ConnectionURL"); conn = DriverManager.getConnection(url, props); ResultSet rs = null; Statement s = conn.createStatement(); if (LOG.isDebugEnabled()) { LOG.debug("Connected to metastore database "); } String mdbPath = HiveTestEnvSetup.HIVE_ROOT + "/data/files/tpcds-perf/metastore_export/"; // Setup the table column stats BufferedReader br = new BufferedReader(new FileReader(new File( HiveTestEnvSetup.HIVE_ROOT + "/metastore/scripts/upgrade/derby/022-HIVE-11107.derby.sql"))); String command; s.execute("DROP TABLE APP.TABLE_PARAMS"); s.execute("DROP TABLE APP.TAB_COL_STATS"); // Create the column stats table while ((command = br.readLine()) != null) { if (!command.endsWith(";")) { continue; } if (LOG.isDebugEnabled()) { LOG.debug("Going to run command : " + command); } PreparedStatement psCommand = conn.prepareStatement(command.substring(0, command.length() - 1)); psCommand.execute(); psCommand.close(); if (LOG.isDebugEnabled()) { LOG.debug("successfully completed " + command); } } br.close(); java.nio.file.Path tabColStatsCsv = FileSystems.getDefault().getPath(mdbPath, "csv", "TAB_COL_STATS.txt.bz2"); java.nio.file.Path tabParamsCsv = FileSystems.getDefault().getPath(mdbPath, "csv", "TABLE_PARAMS.txt.bz2"); // Set up the foreign key constraints properly in the TAB_COL_STATS data java.nio.file.Path tmpFileLoc1 = FileSystems.getDefault().getPath(tmpBaseDir, "TAB_COL_STATS.txt"); java.nio.file.Path tmpFileLoc2 = FileSystems.getDefault().getPath(tmpBaseDir, "TABLE_PARAMS.txt"); class MyComp implements Comparator<String> { @Override public int compare(String str1, String str2) { if (str2.length() != str1.length()) { return str2.length() - str1.length(); } return str1.compareTo(str2); } } final SortedMap<String, Integer> tableNameToID = new TreeMap<String, Integer>(new MyComp()); rs = s.executeQuery("SELECT * FROM APP.TBLS"); while (rs.next()) { String tblName = rs.getString("TBL_NAME"); Integer tblId = rs.getInt("TBL_ID"); tableNameToID.put(tblName, tblId); if (LOG.isDebugEnabled()) { LOG.debug("Resultset : " + tblName + " | " + tblId); } } final Map<String, Map<String, String>> data = new HashMap<>(); rs = s.executeQuery("select TBLS.TBL_NAME, a.COLUMN_NAME, a.TYPE_NAME from " + "(select COLUMN_NAME, TYPE_NAME, SDS.SD_ID from APP.COLUMNS_V2 join APP.SDS on SDS.CD_ID = COLUMNS_V2.CD_ID) a" + " join APP.TBLS on TBLS.SD_ID = a.SD_ID"); while (rs.next()) { String tblName = rs.getString(1); String colName = rs.getString(2); String typeName = rs.getString(3); Map<String, String> cols = data.get(tblName); if (null == cols) { cols = new HashMap<>(); } cols.put(colName, typeName); data.put(tblName, cols); } BufferedReader reader = new BufferedReader(new InputStreamReader( new BZip2CompressorInputStream(Files.newInputStream(tabColStatsCsv, StandardOpenOption.READ)))); Stream<String> replaced = reader.lines().parallel().map(str -> { String[] splits = str.split(","); String tblName = splits[0]; String colName = splits[1]; Integer tblID = tableNameToID.get(tblName); StringBuilder sb = new StringBuilder( "default@" + tblName + "@" + colName + "@" + data.get(tblName).get(colName) + "@"); for (int i = 2; i < splits.length; i++) { sb.append(splits[i] + "@"); } // Add tbl_id and empty bitvector return sb.append(tblID).append("@").toString(); }); Files.write(tmpFileLoc1, (Iterable<String>) replaced::iterator); replaced.close(); reader.close(); BufferedReader reader2 = new BufferedReader(new InputStreamReader( new BZip2CompressorInputStream(Files.newInputStream(tabParamsCsv, StandardOpenOption.READ)))); final Map<String, String> colStats = new ConcurrentHashMap<>(); Stream<String> replacedStream = reader2.lines().parallel().map(str -> { String[] splits = str.split("_@"); String tblName = splits[0]; Integer tblId = tableNameToID.get(tblName); Map<String, String> cols = data.get(tblName); StringBuilder sb = new StringBuilder(); sb.append("{\"COLUMN_STATS\":{"); for (String colName : cols.keySet()) { sb.append("\"" + colName + "\":\"true\","); } sb.append("},\"BASIC_STATS\":\"true\"}"); colStats.put(tblId.toString(), sb.toString()); return tblId.toString() + "@" + splits[1]; }); Files.write(tmpFileLoc2, (Iterable<String>) replacedStream::iterator); Files.write(tmpFileLoc2, (Iterable<String>) colStats.entrySet().stream() .map(map -> map.getKey() + "@COLUMN_STATS_ACCURATE@" + map.getValue())::iterator, StandardOpenOption.APPEND); replacedStream.close(); reader2.close(); // Load the column stats and table params with 30 TB scale String importStatement1 = "CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE(null, '" + "TAB_COL_STATS" + "', '" + tmpFileLoc1.toAbsolutePath().toString() + "', '@', null, 'UTF-8', 1)"; String importStatement2 = "CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE(null, '" + "TABLE_PARAMS" + "', '" + tmpFileLoc2.toAbsolutePath().toString() + "', '@', null, 'UTF-8', 1)"; PreparedStatement psImport1 = conn.prepareStatement(importStatement1); if (LOG.isDebugEnabled()) { LOG.debug("Going to execute : " + importStatement1); } psImport1.execute(); psImport1.close(); if (LOG.isDebugEnabled()) { LOG.debug("successfully completed " + importStatement1); } PreparedStatement psImport2 = conn.prepareStatement(importStatement2); if (LOG.isDebugEnabled()) { LOG.debug("Going to execute : " + importStatement2); } psImport2.execute(); psImport2.close(); if (LOG.isDebugEnabled()) { LOG.debug("successfully completed " + importStatement2); } s.execute("ALTER TABLE APP.TAB_COL_STATS ADD COLUMN CAT_NAME VARCHAR(256)"); s.execute("update APP.TAB_COL_STATS set CAT_NAME = '" + Warehouse.DEFAULT_CATALOG_NAME + "'"); s.close(); conn.close(); } catch (Exception e) { throw new RuntimeException("error while loading tpcds metastore dump", e); } }
From source file:de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorage.java
/** * Closes this object storage. After the storage is closed, objects cannot * be persisted or retrieved anymore./* w ww .j av a 2s . c om*/ */ public void close() { try { classMap.commit(); if (!FileSystems.getDefault().equals(fileSystem)) { fileSystem.close(); } } catch (IOException ex) { throw new IllegalStateException(ex); } }
From source file:it.infn.ct.futuregateway.apiserver.APIContextListener.java
@Override public final void contextInitialized(final ServletContextEvent sce) { log.info("Creation of the Hibernate SessionFactory for the context"); try {/* w ww . jav a2s . c o m*/ entityManagerFactory = Persistence .createEntityManagerFactory("it.infn.ct.futuregateway.apiserver.container"); } catch (Exception ex) { log.warn("Resource 'jdbc/FutureGatewayDB' not accessuible or" + " not properly configured for the application. An" + " alternative resource is created on the fly."); entityManagerFactory = Persistence.createEntityManagerFactory("it.infn.ct.futuregateway.apiserver.app"); } sce.getServletContext().setAttribute(Constants.SESSIONFACTORY, entityManagerFactory); String path = sce.getServletContext().getInitParameter("CacheDir"); if (path == null || path.isEmpty()) { path = sce.getServletContext().getRealPath("/") + ".." + FileSystems.getDefault().getSeparator() + ".." + FileSystems.getDefault().getSeparator() + "FutureGatewayData"; } log.info("Created the cache directory: " + path); sce.getServletContext().setAttribute(Constants.CACHEDIR, path); try { Files.createDirectories(Paths.get(path)); log.info("Cache dir enabled"); } catch (FileAlreadyExistsException faee) { log.debug("Message for '" + path + "':" + faee.getMessage()); log.info("Cache dir enabled"); } catch (Exception e) { log.error("Impossible to initialise the temporary store"); } ExecutorService tpe; try { Context ctx = new InitialContext(); tpe = (ExecutorService) ctx.lookup("java:comp/env/threads/Submitter"); } catch (NamingException ex) { log.warn("Submitter thread not defined in the container. A thread " + "pool is created using provided configuration parameters " + "and defaults values"); int threadPoolSize = Constants.DEFAULTTHREADPOOLSIZE; try { threadPoolSize = Integer .parseInt(sce.getServletContext().getInitParameter("SubmissioneThreadPoolSize")); } catch (NumberFormatException nfe) { log.info("Parameter 'SubmissioneThreadPoolSize' has a wrong" + " value or it is not present. Default value " + "10 is used"); } tpe = ThreadPoolFactory.getThreadPool(threadPoolSize, Constants.MAXTHREADPOOLSIZETIMES * threadPoolSize, Constants.MAXTHREADIDLELIFE); } sce.getServletContext().setAttribute(Constants.SUBMISSIONPOOL, tpe); }
From source file:io.stallion.dataAccess.file.TextFilePersister.java
@Override public T doFetchOne(File file) { Path path = FileSystems.getDefault().getPath(file.getAbsolutePath()); BufferedReader reader = null; try {//from ww w .j ava 2 s. c o m reader = Files.newBufferedReader(path, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } int lineCount = 0; StringBuffer buffer = new StringBuffer(); for (int i : safeLoop(50000)) { String line = null; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { break; } buffer.append(line + "\n"); lineCount = i; } if (lineCount < 2) { return null; } String fileContent = buffer.toString(); return fromString(fileContent, path); }
From source file:RestoreService.java
public static void setAdvancedAttributes(final VOBackupFile voBackupFile, final File file) throws IOException { // advanced attributes // owner//from ww w . j ava2 s . c o m if (StringUtils.isNotBlank(voBackupFile.getOwner())) { try { UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService(); UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(voBackupFile.getOwner()); Files.setOwner(file.toPath(), userPrincipal); } catch (UserPrincipalNotFoundException e) { logger.warn("Cannot set owner {}", voBackupFile.getOwner()); } } if (Files.getFileStore(file.toPath()).supportsFileAttributeView(DosFileAttributeView.class) && BooleanUtils.isTrue(voBackupFile.getDosAttr())) { Files.setAttribute(file.toPath(), "dos:hidden", BooleanUtils.isTrue(voBackupFile.getDosHidden())); Files.setAttribute(file.toPath(), "dos:archive", BooleanUtils.isTrue(voBackupFile.getDosArchive())); Files.setAttribute(file.toPath(), "dos:readonly", BooleanUtils.isTrue(voBackupFile.getDosReadOnly())); Files.setAttribute(file.toPath(), "dos:system", BooleanUtils.isTrue(voBackupFile.getDosSystem())); } if (Files.getFileStore(file.toPath()).supportsFileAttributeView(PosixFileAttributeView.class) && BooleanUtils.isTrue(voBackupFile.getPosixAttr())) { try { UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService(); GroupPrincipal groupPrincipal = lookupService .lookupPrincipalByGroupName(voBackupFile.getPosixGroup()); Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS) .setGroup(groupPrincipal); } catch (UserPrincipalNotFoundException e) { logger.warn("Cannot set group {}", voBackupFile.getOwner()); } if (StringUtils.isNotBlank(voBackupFile.getPosixPermitions())) { Set<PosixFilePermission> perms = PosixFilePermissions.fromString(voBackupFile.getPosixPermitions()); Files.setPosixFilePermissions(file.toPath(), perms); } } }
From source file:eu.uqasar.web.upload.FileUploadUtil.java
Path getNewFileName(FileUpload file, User user, boolean overwrite) throws IOException { Path target;/* w w w. ja va2 s.co m*/ String uploadedFileFileName = file.getClientFileName(); if (overwrite) { target = FileSystems.getDefault().getPath(getUserUploadFolder(user).toString(), uploadedFileFileName); } else { final String extensionPart = FilenameUtils.getExtension(uploadedFileFileName); final String extension = StringUtils.isEmpty(extensionPart) ? "" : "." + extensionPart; // we add a dot (".") before the UUID, so +1 final int UUID_LENGTH = 1 + 36; // extension length is given out of extension length + the dot (".txt" == 4, no extension == 0) final int EXTENSION_LENGTH = extension.length(); // MAX file name length is 255 - UUID part - Extension part final int MAX_BASE_FILENAME_LENGTH = 255 - UUID_LENGTH - EXTENSION_LENGTH; // shorten file name to no longer than max length, calculated above final String fileNameWithoutExtension = StringUtils .left(FilenameUtils.getBaseName(uploadedFileFileName), MAX_BASE_FILENAME_LENGTH); // generate new file name out of shortened base name + "." + UUID + any extension (including ".") final String targetFileName = String.format("%s.%s%s", fileNameWithoutExtension, UUID.randomUUID().toString(), extension); target = FileSystems.getDefault().getPath(getUserUploadFolder(user).toString(), targetFileName); } return target; }
From source file:com.kamike.misc.FsUtils.java
public static void createDirectory(String dstPath) { Properties props = System.getProperties(); // String osName = props.getProperty("os.name"); //??? Path newdir = FileSystems.getDefault().getPath(dstPath); boolean pathExists = Files.exists(newdir, new LinkOption[] { LinkOption.NOFOLLOW_LINKS }); if (!pathExists) { Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwxrwx"); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); try {//from w w w. java 2 s.c om if (!osName.contains("Windows")) { Files.createDirectories(newdir, attr); } else { Files.createDirectories(newdir); } } catch (Exception e) { System.err.println(e); } } }