List of usage examples for java.nio.file Files size
public static long size(Path path) throws IOException
From source file:org.apache.nifi.controller.service.ControllerServiceLoader.java
public List<ControllerServiceNode> loadControllerServices(final ControllerServiceProvider provider) throws IOException { final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); InputStream fis = null;/*from ww w. j a v a2s .c o m*/ BufferedInputStream bis = null; documentBuilderFactory.setNamespaceAware(true); final List<ControllerServiceNode> services = new ArrayList<>(); try { final URL configurationResource = this.getClass().getResource("/ControllerServiceConfiguration.xsd"); if (configurationResource == null) { throw new NullPointerException("Unable to load XML Schema for ControllerServiceConfiguration"); } final Schema schema = schemaFactory.newSchema(configurationResource); documentBuilderFactory.setSchema(schema); final DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); builder.setErrorHandler(new org.xml.sax.ErrorHandler() { @Override public void fatalError(final SAXParseException err) throws SAXException { logger.error("Config file line " + err.getLineNumber() + ", col " + err.getColumnNumber() + ", uri " + err.getSystemId() + " :message: " + err.getMessage()); if (logger.isDebugEnabled()) { logger.error("Error Stack Dump", err); } throw err; } @Override public void error(final SAXParseException err) throws SAXParseException { logger.error("Config file line " + err.getLineNumber() + ", col " + err.getColumnNumber() + ", uri " + err.getSystemId() + " :message: " + err.getMessage()); if (logger.isDebugEnabled()) { logger.error("Error Stack Dump", err); } throw err; } @Override public void warning(final SAXParseException err) throws SAXParseException { logger.warn(" Config file line " + err.getLineNumber() + ", uri " + err.getSystemId() + " : message : " + err.getMessage()); if (logger.isDebugEnabled()) { logger.warn("Warning stack dump", err); } throw err; } }); //if controllerService.xml does not exist, create an empty file... fis = Files.newInputStream(this.serviceConfigXmlPath, StandardOpenOption.READ); bis = new BufferedInputStream(fis); if (Files.size(this.serviceConfigXmlPath) > 0) { final Document document = builder.parse(bis); final NodeList servicesNodes = document.getElementsByTagName("services"); final Element servicesElement = (Element) servicesNodes.item(0); final List<Element> serviceNodes = DomUtils.getChildElementsByTagName(servicesElement, "service"); for (final Element serviceElement : serviceNodes) { //get properties for the specific controller task - id, name, class, //and schedulingPeriod must be set final String serviceId = DomUtils.getChild(serviceElement, "identifier").getTextContent() .trim(); final String serviceClass = DomUtils.getChild(serviceElement, "class").getTextContent().trim(); //set the class to be used for the configured controller task final ControllerServiceNode serviceNode = provider.createControllerService(serviceClass, serviceId, false); //optional task-specific properties for (final Element optionalProperty : DomUtils.getChildElementsByTagName(serviceElement, "property")) { final String name = optionalProperty.getAttribute("name").trim(); final String value = optionalProperty.getTextContent().trim(); serviceNode.setProperty(name, value); } services.add(serviceNode); provider.enableControllerService(serviceNode); } } } catch (SAXException | ParserConfigurationException sxe) { throw new IOException(sxe); } finally { FileUtils.closeQuietly(fis); FileUtils.closeQuietly(bis); } return services; }
From source file:com.cami.web.controller.FileController.java
/** * ************************************************* * URL: /appel-offre/file/get/{value} get(): get file as an attachment * * @param response : passed by the server * @param value : value from the URL/*from w w w . j a v a 2 s. co m*/ * @return void ************************************************** */ @RequestMapping(value = "/get/{value}", method = RequestMethod.GET) public void get(HttpServletResponse response, @PathVariable String value) { System.out.println(value); String savedFileName = getSavedFileName(SAVE_DIRECTORY, value); File file = new File(savedFileName); Path source = Paths.get(savedFileName); FileMeta getFile = new FileMeta(); try { getFile.setFileName(file.getName()); getFile.setFileSize(Files.size(source) / 1024 + " Kb"); getFile.setFileType(Files.probeContentType(source)); response.setContentType(getFile.getFileType()); response.setHeader("Content-disposition", "attachment; filename=\"" + getFile.getFileName() + "\""); FileCopyUtils.copy(Files.readAllBytes(source), response.getOutputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.opensingular.form.wicket.mapper.attachment.upload.FileUploadManager.java
public FileUploadInfo createFile(UploadInfo uploadInfo, String fileName, InputStream input) throws IOException { getLogger().debug("createFile({},{},{})", uploadInfo.getUploadId(), fileName, input); final Path path; final IAttachmentPersistenceHandler handler; final IAttachmentRef attachment; final FileUploadInfo info; final File file; handler = uploadInfo.getPersistenceHandlerSupplier().get(); path = uploadPathHandler.getLocalFilePath(attachmentKeyFactory.make().toString()); file = path.toFile();// ww w . j av a2 s. c o m file.deleteOnExit(); DigestInputStream din = HashUtil.toSHA1InputStream(input); Files.copy(din, path); attachment = handler.addAttachment(file, Files.size(path), fileName, HashUtil.bytesToBase16(din.getMessageDigest().digest())); info = new FileUploadInfo(attachment); fileUploadInfoRepository.add(info); return info; }
From source file:com.spectralogic.ds3client.integration.PutJobManagement_Test.java
@SuppressWarnings("deprecation") @Test/* ww w . ja v a 2 s . c o m*/ public void nakedS3Put() throws IOException, SignatureException, XmlProcessingException, URISyntaxException { try { final Path beowulfPath = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + "beowulf.txt"); final SeekableByteChannel beowulfChannel = new ResourceObjectPutter(RESOURCE_BASE_NAME) .buildChannel("beowulf.txt"); final PutObjectResponse putObjectResponse = client.putObject( new PutObjectRequest(BUCKET_NAME, "beowulf.txt", beowulfChannel, Files.size(beowulfPath))); assertThat(putObjectResponse.getStatusCode(), is(200)); } finally { deleteAllContents(client, BUCKET_NAME); } }
From source file:com.cloudbees.jenkins.support.api.FileContent.java
private boolean isBinary() { try (InputStream in = getInputStream()) { long size = Files.size(file.toPath()); if (size == 0) { // Empty file, so no need to check return true; }/*from w w w. j a v a2s .c om*/ byte[] b = new byte[(size < StreamUtils.DEFAULT_PROBE_SIZE ? (int) size : StreamUtils.DEFAULT_PROBE_SIZE)]; int read = in.read(b); if (read != b.length) { // Something went wrong, so better not to read line by line return true; } return StreamUtils.isNonWhitespaceControlCharacter(b); } catch (IOException e) { // If cannot be checked, then considered as binary, so we do not // read line by line return true; } }
From source file:com.dianping.resource.io.PathResource.java
/** * This implementation returns the underlying File's length. *//*from ww w . ja v a 2 s.c om*/ @Override public long contentLength() throws IOException { return Files.size(this.path); }
From source file:com.cirrus.server.osgi.service.local.LocalStorageService.java
@Override public CirrusFileData transferFile(final String filePath, final long fileSize, final InputStream inputStream) throws ServiceRequestFailedException { final Path newPath = Paths.get(this.getGlobalContext().getRootPath(), filePath); try {/*from www. j ava2 s .c om*/ final Path createFilePath = Files.createFile(newPath); try (final OutputStream outputStream = Files.newOutputStream(createFilePath)) { IOUtils.copy(inputStream, outputStream); } return new CirrusFileData(createFilePath.toString(), Files.size(createFilePath)); } catch (final IOException e) { throw new ServiceRequestFailedException(e); } }
From source file:org.tinymediamanager.core.movie.tasks.MovieExtraImageFetcher.java
private void downloadArtwork(MediaFileType type, String basename) { String artworkUrl = movie.getArtworkUrl(type); if (StringUtils.isBlank(artworkUrl)) { return;//from w ww . jav a2s. c o m } String filename = basename; if (!filename.isEmpty()) { filename += "-"; } try { String oldFilename = movie.getArtworkFilename(type); // we are lucky and have chosen our enums wisely - except the discart :( if (type == MediaFileType.DISCART) { filename += "disc." + FilenameUtils.getExtension(artworkUrl); } else { filename += type.name().toLowerCase(Locale.ROOT) + "." + FilenameUtils.getExtension(artworkUrl); } movie.removeAllMediaFiles(type); // debug message LOGGER.debug("writing " + type + " " + filename); // fetch and store images Url url1 = new Url(artworkUrl); Path tempFile = movie.getPathNIO().resolve(filename + ".part"); FileOutputStream outputStream = new FileOutputStream(tempFile.toFile()); InputStream is = url1.getInputStream(); IOUtils.copy(is, outputStream); outputStream.flush(); try { outputStream.getFD().sync(); // wait until file has been completely written // give it a few milliseconds Thread.sleep(150); } catch (Exception e) { // empty here -> just not let the thread crash } outputStream.close(); is.close(); // has tmm been shut down? if (Thread.interrupted()) { return; } // check if the file has been downloaded if (!Files.exists(tempFile) || Files.size(tempFile) == 0) { throw new Exception("0byte file downloaded: " + filename); } // delete the old one if exisiting if (StringUtils.isNotBlank(oldFilename)) { Path oldFile = movie.getPathNIO().resolve(oldFilename); Utils.deleteFileSafely(oldFile); } // delete new destination if existing Path destinationFile = movie.getPathNIO().resolve(filename); Utils.deleteFileSafely(destinationFile); // move the temp file to the expected filename if (!Utils.moveFileSafe(tempFile, destinationFile)) { throw new Exception("renaming temp file failed: " + filename); } movie.setArtwork(destinationFile, type); movie.callbackForWrittenArtwork(MediaFileType.getMediaArtworkType(type)); movie.saveToDb(); } catch (Exception e) { if (e instanceof InterruptedException) { // only warning LOGGER.warn("interrupted image download"); } else { LOGGER.error("fetch image: " + e.getMessage()); } // remove temp file Path tempFile = movie.getPathNIO().resolve(filename + ".part"); if (Files.exists(tempFile)) { Utils.deleteFileSafely(tempFile); } } }
From source file:ec.edu.chyc.manejopersonal.managebean.GestorContrato.java
public String initModificarContrato(Long id) { //contrato = contratoController. inicializarManejoContrato();/*from w w w. j a v a2s .c om*/ contrato = contratoController.findContrato(id); listaProyectos = new ArrayList(contrato.getProyectosCollection()); if (contrato.getTipoProfesor() != null) { esProfesor = true; } /*if (!esProfesor) { //si no es profesor, asignar el unico proyecto relacionado al contrato, a la variable contrato.proyecto para poder obtener de una sola Proyecto unicoProyecto = contrato.getProyectosCollection().stream().findFirst().get(); contrato.setProyecto(unicoProyecto); }*/ modoModificar = true; try { Path pathArchivoSubido = ServerUtils.getPathContratos().resolve(contrato.getArchivoContrato()); if (Files.isRegularFile(pathArchivoSubido) && Files.exists(pathArchivoSubido)) { Long size = Files.size(pathArchivoSubido); tamanoArchivo = ServerUtils.humanReadableByteCount(size); } else { tamanoArchivo = ""; } } catch (IOException ex) { Logger.getLogger(GestorContrato.class.getName()).log(Level.SEVERE, null, ex); } return "manejoContratos"; }
From source file:org.fao.geonet.api.records.attachments.FilesystemStore.java
@Override public List<MetadataResource> getResources(ServiceContext context, String metadataUuid, MetadataResourceVisibility visibility, String filter) throws Exception { ApplicationContext _appContext = ApplicationContextHolder.get(); String metadataId = getAndCheckMetadataId(metadataUuid); GeonetworkDataDirectory dataDirectory = _appContext.getBean(GeonetworkDataDirectory.class); SettingManager settingManager = _appContext.getBean(SettingManager.class); AccessManager accessManager = _appContext.getBean(AccessManager.class); boolean canEdit = accessManager.canEdit(context, metadataId); if (visibility == MetadataResourceVisibility.PRIVATE && !canEdit) { throw new SecurityException(String.format( "User does not have privileges to get the list of '%s' resources for metadata '%s'.", visibility, metadataUuid)); }/*www .j ava 2 s .c o m*/ Path metadataDir = Lib.resource.getMetadataDir(dataDirectory, metadataId); Path resourceTypeDir = metadataDir.resolve(visibility.toString()); List<MetadataResource> resourceList = new ArrayList<>(); if (filter == null) { filter = FilesystemStore.DEFAULT_FILTER; } try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(resourceTypeDir, filter)) { for (Path path : directoryStream) { MetadataResource resource = new FilesystemStoreResource( UrlEscapers.urlFragmentEscaper().escape(metadataUuid) + "/attachments/" + UrlEscapers.urlFragmentEscaper().escape(path.getFileName().toString()), settingManager.getNodeURL() + "api/records/", visibility, Files.size(path)); resourceList.add(resource); } } catch (IOException ignored) { } Collections.sort(resourceList, MetadataResourceVisibility.sortByFileName); return resourceList; }