List of usage examples for java.io File toPath
public Path toPath()
From source file:com.sastix.cms.server.services.content.ResourceServiceTest.java
@Test public void shouldCreateResourceFromExternalUri() throws Exception { URL localFile = getClass().getClassLoader().getResource("./logo.png"); CreateResourceDTO createResourceDTO = new CreateResourceDTO(); createResourceDTO.setResourceAuthor("Demo Author"); createResourceDTO.setResourceExternalURI(localFile.getProtocol() + "://" + localFile.getFile()); createResourceDTO.setResourceMediaType("image/png"); createResourceDTO.setResourceName("logo.png"); createResourceDTO.setResourceTenantId("zaq12345"); ResourceDTO resourceDTO = resourceService.createResource(createResourceDTO); String resourceUri = resourceDTO.getResourceURI(); //Extract TenantID final String tenantID = resourceUri.substring(resourceUri.lastIndexOf('-') + 1, resourceUri.indexOf("/")); final Path responseFile = hashedDirectoryService.getDataByURI(resourceUri, tenantID); File file = responseFile.toFile(); byte[] actualBytes = Files.readAllBytes(file.toPath()); byte[] expectedBytes = Files.readAllBytes(Paths.get(localFile.getPath())); Assert.assertArrayEquals(expectedBytes, actualBytes); }
From source file:cz.etnetera.reesmo.writer.storage.FileSystemStorage.java
protected String createModelId(File modelDir) { return baseDir.toPath().relativize(modelDir.toPath()).normalize().toString().replaceAll(File.separator, "/"); }
From source file:com.facebook.buck.step.fs.ZstdStepTest.java
@Test public void testZstdStep() throws Exception { Path sourceFileOriginal = TestDataHelper.getTestDataScenario(this, "compression_test").resolve("step.data"); Path sourceFile = tmp.newFile("step.data").toPath(); Files.copy(sourceFileOriginal, sourceFile, StandardCopyOption.REPLACE_EXISTING); File destinationFile = tmp.newFile("step.data.zstd"); ZstdStep step = new ZstdStep(TestProjectFilesystems.createProjectFilesystem(tmp.getRoot().toPath()), sourceFile, destinationFile.toPath()); ExecutionContext context = TestExecutionContext.newInstance(); assertEquals(0, step.execute(context).getExitCode()); ByteSource original = PathByteSource.asByteSource(sourceFileOriginal); ByteSource decompressed = new ByteSource() { @Override/*from w w w. j av a 2 s . c o m*/ public InputStream openStream() throws IOException { return new ZstdCompressorInputStream(new FileInputStream(destinationFile)); } }; assertFalse(Files.exists(sourceFile)); assertTrue("Decompressed file must be identical to original.", original.contentEquals(decompressed)); }
From source file:com.liferay.blade.cli.command.ConvertThemeCommand.java
public void importTheme(String themePath) throws Exception { Process process = BladeUtil.startProcess("node -v", _themesDir); int nodeJSInstalledChecker = process.waitFor(); if (nodeJSInstalledChecker != 0) { _bladeCLI.error("Please check that Node.js properly installed and on the user path."); return;/* w w w . j a v a 2s . c o m*/ } process = BladeUtil.startProcess("yo liferay-theme:import -p \"" + themePath + "\" -c " + _compassSupport(themePath) + " --skip-install", _themesDir, _bladeCLI.out(), _bladeCLI.error()); int errCode = process.waitFor(); if (errCode == 0) { _bladeCLI.out("Theme " + themePath + " migrated successfully"); File theme = new File(themePath); FileUtil.deleteDir(theme.toPath()); } else { _bladeCLI.error("blade exited with code: " + errCode); } }
From source file:de.jwi.jfm.FileWrapper.java
public String getAttributes() throws IOException { FileSystem fileSystem = FileSystems.getDefault(); Set<String> fileSystemViews = fileSystem.supportedFileAttributeViews(); File file = getFile(); Path p = file.toPath(); try {//from www . ja v a2 s . c o m if (fileSystemViews.contains("posix")) { Set<PosixFilePermission> posixFilePermissions = Files.getPosixFilePermissions(p, LinkOption.NOFOLLOW_LINKS); PosixFileAttributes attrs = Files.getFileAttributeView(p, PosixFileAttributeView.class) .readAttributes(); String owner = attrs.owner().toString(); String group = attrs.group().toString(); String permissions = PosixFilePermissions.toString(attrs.permissions()); String res = String.format("%s %s %s", permissions, owner, group); return res; } else if (fileSystemViews.contains("dos")) { StringWriter sw = new StringWriter(); DosFileAttributeView attributeView = Files.getFileAttributeView(p, DosFileAttributeView.class); DosFileAttributes dosFileAttributes = null; dosFileAttributes = attributeView.readAttributes(); if (dosFileAttributes.isArchive()) { sw.append('A'); } if (dosFileAttributes.isHidden()) { sw.append('H'); } if (dosFileAttributes.isReadOnly()) { sw.append('R'); } if (dosFileAttributes.isSystem()) { sw.append('S'); } return sw.toString(); } } catch (Exception e) { e.printStackTrace(); } return ""; }
From source file:edu.chalmers.dat076.moviefinder.service.FileThreadServiceImpl.java
@PostConstruct @Transactional/*from www . j a v a2 s .c o m*/ public void init() { threads = new LinkedList<>(); Iterable<ListeningPath> paths = listeningPathRepository.findAll(); List<Path> checkPaths = new LinkedList<>(); for (ListeningPath p : paths) { File f = new File(p.getListeningPath()); if (f.exists() && f.isDirectory()) { addListeningPath(f.toPath()); checkPaths.add(f.toPath()); } else { databaseHelper.removePath(f.toPath()); movieDatabaseHelper.removeFile(f.toPath()); } } movieDatabaseHelper.setPaths(checkPaths); }
From source file:com.hortonworks.registries.util.HdfsFileStorageTest.java
@Test public void testUploadJar() throws Exception { Map<String, String> config = new HashMap<>(); config.put(HdfsFileStorage.CONFIG_FSURL, "file:///"); fileStorage.init(config);//from ww w .j av a 2s . c om File file = File.createTempFile("test", ".tmp"); file.deleteOnExit(); List<String> lines = Arrays.asList("test-line-1", "test-line-2"); Files.write(file.toPath(), lines, Charset.forName("UTF-8")); String jarFileName = "test.jar"; fileStorage.deleteFile(jarFileName); fileStorage.uploadFile(new FileInputStream(file), jarFileName); InputStream inputStream = fileStorage.downloadFile(jarFileName); List<String> actual = IOUtils.readLines(inputStream); Assert.assertEquals(lines, actual); }
From source file:media_organizer.MediaInspector.java
public String get_file_creation_time(File file) throws IOException { // Find file creation time , etc Path f = file.toPath(); BasicFileAttributes attr;/*from ww w . ja v a2s . c om*/ String fileCreationTime = null; try { attr = Files.readAttributes(f, BasicFileAttributes.class); fileCreationTime = attr.creationTime().toString(); //System.out.println("create time: " + attr.creationTime()); return fileCreationTime.replaceAll("[-:T.]", "_").replaceAll("[Z]", ""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw e; } }
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;//w ww . ja 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:com.anritsu.mcreleaseportal.utils.FileUpload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . java 2 s. c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.setAttribute("mcPackage", null); PrintWriter pw = response.getWriter(); response.setContentType("text/plain"); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); // Save input stream file for later use File dir = new File(Configuration.getInstance().getSavePath()); if (!dir.exists() && !dir.isDirectory()) { dir.mkdir(); LOGGER.log(Level.INFO, "Changes.xml archive directory was created at " + dir.getAbsolutePath()); } String fileName = request.getSession().getId() + "_" + System.currentTimeMillis(); File file = new File(dir, fileName); file.createNewFile(); Path path = file.toPath(); Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING); LOGGER.log(Level.INFO, "changes.xml saved on disk as: " + file.getAbsolutePath()); // Save filename to session for next calls session.setAttribute("xmlFileLocation", file.getAbsolutePath()); LOGGER.log(Level.INFO, "changes.xml saved on session as: fileName:" + file.getAbsolutePath()); // Cleanup stream.close(); } } catch (FileUploadException | IOException | RuntimeException e) { pw.println( "An error occurred when trying to process uploaded file! \n Please check the file consistency and try to re-submit. \n If the error persist pleace contact system administrator!"); } }