List of usage examples for org.apache.commons.vfs2 FileContent getSize
long getSize() throws FileSystemException;
From source file:com.yenlo.synapse.transport.vfs.VFSTransportListener.java
/** * Process a single file through Axis2// w w w .ja va2s. c o m * @param entry the PollTableEntry for the file (or its parent directory or archive) * @param file the file that contains the actual message pumped into Axis2 * @throws AxisFault on error */ private void processFile(PollTableEntry entry, FileObject file) throws AxisFault { try { FileContent content = file.getContent(); String fileName = file.getName().getBaseName(); String filePath = file.getName().getPath(); String fileURI = file.getName().getURI(); metrics.incrementBytesReceived(content.getSize()); Map<String, Object> transportHeaders = new HashMap<String, Object>(); transportHeaders.put(VFSConstants.FILE_PATH, filePath); transportHeaders.put(VFSConstants.FILE_NAME, fileName); transportHeaders.put(VFSConstants.FILE_URI, fileURI); try { transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize()); transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime()); } catch (FileSystemException ignore) { } MessageContext msgContext = entry.createMessageContext(); String contentType = entry.getContentType(); if (BaseUtils.isBlank(contentType)) { if (file.getName().getExtension().toLowerCase().endsWith(".xml")) { contentType = "text/xml"; } else if (file.getName().getExtension().toLowerCase().endsWith(".txt")) { contentType = "text/plain"; } } else { // Extract the charset encoding from the configured content type and // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this. String charSetEnc = null; try { if (contentType != null) { charSetEnc = new ContentType(contentType).getParameter("charset"); } } catch (ParseException ex) { // ignore } msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); } // if the content type was not found, but the service defined it.. use it if (contentType == null) { if (entry.getContentType() != null) { contentType = entry.getContentType(); } else if (VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE) != null) { contentType = VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE); } } // does the service specify a default reply file URI ? String replyFileURI = entry.getReplyFileURI(); if (replyFileURI != null) { msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, new VFSOutTransportInfo(replyFileURI, entry.isFileLockingEnabled())); } // Determine the message builder to use Builder builder; if (contentType == null) { log.debug("No content type specified. Using SOAP builder."); builder = new SOAPBuilder(); } else { int index = contentType.indexOf(';'); String type = index > 0 ? contentType.substring(0, index) : contentType; builder = BuilderUtil.getBuilderFromSelector(type, msgContext); if (builder == null) { if (log.isDebugEnabled()) { log.debug("No message builder found for type '" + type + "'. Falling back to SOAP."); } builder = new SOAPBuilder(); } } // set the message payload to the message context InputStream in; ManagedDataSource dataSource; if (builder instanceof DataSourceMessageBuilder && entry.isStreaming()) { in = null; dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType)); } else { in = new AutoCloseInputStream(content.getInputStream()); dataSource = null; } try { OMElement documentElement; if (in != null) { documentElement = builder.processDocument(in, contentType, msgContext); } else { documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType, msgContext); } msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); handleIncomingMessage(msgContext, transportHeaders, null, //* SOAP Action - not applicable *// contentType); } finally { if (dataSource != null) { dataSource.destroy(); } } if (log.isDebugEnabled()) { log.debug("Processed file : " + file + " of Content-type : " + contentType); } } catch (FileSystemException e) { handleException("Error reading file content or attributes : " + file, e); } finally { try { file.close(); } catch (FileSystemException warn) { // log.warn("Cannot close file after processing : " + file.getName().getPath(), warn); // ignore the warning, since we handed over the stream close job to AutocloseInputstream.. } } }
From source file:net.sf.jabb.web.action.VfsTreeAction.java
/** * It transforms FileObject into JsTreeNodeData. * @param file the file whose information will be encapsulated in the node data structure. * @return The node data structure which presents the file. * @throws FileSystemException /*from w w w .j av a 2 s. co m*/ */ protected JsTreeNodeData populateTreeNodeData(FileObject file, boolean noChild, String relativePath) throws FileSystemException { JsTreeNodeData node = new JsTreeNodeData(); String baseName = file.getName().getBaseName(); FileContent content = file.getContent(); FileType type = file.getType(); node.setData(baseName); Map<String, Object> attr = new HashMap<String, Object>(); node.setAttr(attr); attr.put("id", relativePath); attr.put("rel", type.getName()); attr.put("fileType", type.getName()); if (content != null) { long fileLastModifiedTime = file.getContent().getLastModifiedTime(); attr.put("fileLastModifiedTime", fileLastModifiedTime); attr.put("fileLastModifiedTimeForDisplay", DateFormat.getDateTimeInstance().format(new Date(fileLastModifiedTime))); if (file.getType() != FileType.FOLDER) { attr.put("fileSize", content.getSize()); attr.put("fileSizeForDisplay", FileUtils.byteCountToDisplaySize(content.getSize())); } } // these fields should not appear in JSON for leaf nodes if (!noChild) { node.setState(JsTreeNodeData.STATE_CLOSED); } return node; }
From source file:com.github.abola.crawler.CrawlerPack.java
/** * ?? Apache Common VFS ???//from ww w . j a v a 2s. co m * * ?? * @see <a href="https://commons.apache.org/proper/commons-vfs/filesystems.html">commons-vfs filesystems</a> */ public String getFromRemote(String uri) { // clear cache fileSystem.getFilesCache().close(); String remoteContent; String remoteEncoding = "utf-8"; log.debug("getFromRemote: Loading remote URI=" + uri); FileContent fileContent; try { FileSystemOptions fsOptions = new FileSystemOptions(); // set userAgent HttpFileSystemConfigBuilder.getInstance().setUserAgent(fsOptions, userAgent); // set cookie if cookies set if (0 < this.cookies.size()) { HttpFileSystemConfigBuilder.getInstance().setCookies(fsOptions, getCookies(uri)); } log.debug("getFromRemote: userAgent=" + userAgent); log.debug("getFromRemote: cookieSize=" + cookies.size()); log.debug("getFromRemote: cookies=" + cookies.toString()); fileContent = fileSystem.resolveFile(uri, fsOptions).getContent(); // 2016-03-22 only pure http/https auto detect encoding if ("http".equalsIgnoreCase(uri.substring(0, 4))) { fileContent.getSize(); // pass a bug {@link https://issues.apache.org/jira/browse/VFS-427} remoteEncoding = fileContent.getContentInfo().getContentEncoding(); } log.debug("getFromRemote: remoteEncoding=" + remoteEncoding + "(auto detect) "); // 2016-03-21 zip file getContentEncoding null if (null == remoteEncoding) remoteEncoding = "utf-8"; if (!"utf".equalsIgnoreCase(remoteEncoding.substring(0, 3))) { log.debug("getFromRemote: remote content encoding=" + remoteEncoding); // force charset encoding if setRemoteEncoding set if (!"utf".equalsIgnoreCase(encoding.substring(0, 3))) { remoteEncoding = encoding; } else { // auto detecting encoding remoteEncoding = detectCharset(IOUtils.toByteArray(fileContent.getInputStream())); log.debug("getFromRemote: real encoding=" + remoteEncoding); } } // ?? Apache VFS ?? // 2016-02-29 fixed remoteContent = IOUtils.toString(fileContent.getInputStream(), remoteEncoding); } catch (FileSystemException fse) { log.warn("getFromRemote: FileSystemException=" + fse.getMessage()); remoteContent = null; } catch (IOException ioe) { // return empty log.warn("getFromRemote: IOException=" + ioe.getMessage()); remoteContent = null; } catch (StringIndexOutOfBoundsException stre) { log.warn("getFromRemote: StringIndexOutOfBoundsException=" + stre.getMessage()); log.warn("getFromRemote: uri=" + uri); log.warn(stre.getMessage()); remoteContent = null; } clearCookies(); log.debug("getFromRemote: remoteContent=\n" + remoteContent); // any exception will return "null" return remoteContent; }
From source file:org.apache.commons.vfs2.example.Shell.java
/** * Does an 'ls' command.//from w w w . j a v a 2s . c o m */ private void ls(final String[] cmd) throws FileSystemException { int pos = 1; final boolean recursive; if (cmd.length > pos && cmd[pos].equals("-R")) { recursive = true; pos++; } else { recursive = false; } final FileObject file; if (cmd.length > pos) { file = mgr.resolveFile(cwd, cmd[pos]); } else { file = cwd; } if (file.getType() == FileType.FOLDER) { // List the contents System.out.println("Contents of " + file.getName()); listChildren(file, recursive, ""); } else { // Stat the file System.out.println(file.getName()); final FileContent content = file.getContent(); System.out.println("Size: " + content.getSize() + " bytes."); final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); final String lastMod = dateFormat.format(new Date(content.getLastModifiedTime())); System.out.println("Last modified: " + lastMod); } }
From source file:org.apache.synapse.transport.vfs.VFSTransportListener.java
/** * Process a single file through Axis2/*from w w w .j av a 2s.c om*/ * @param entry the PollTableEntry for the file (or its parent directory or archive) * @param file the file that contains the actual message pumped into Axis2 * @throws AxisFault on error */ private void processFile(PollTableEntry entry, FileObject file) throws AxisFault { try { FileContent content = file.getContent(); String fileName = file.getName().getBaseName(); String filePath = file.getName().getPath(); String fileURI = file.getName().getURI(); metrics.incrementBytesReceived(content.getSize()); Map<String, Object> transportHeaders = new HashMap<String, Object>(); transportHeaders.put(VFSConstants.FILE_PATH, filePath); transportHeaders.put(VFSConstants.FILE_NAME, fileName); transportHeaders.put(VFSConstants.FILE_URI, fileURI); try { transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize()); transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime()); } catch (FileSystemException ignore) { } MessageContext msgContext = entry.createMessageContext(); String contentType = entry.getContentType(); if (BaseUtils.isBlank(contentType)) { if (file.getName().getExtension().toLowerCase().endsWith(".xml")) { contentType = "text/xml"; } else if (file.getName().getExtension().toLowerCase().endsWith(".txt")) { contentType = "text/plain"; } } else { // Extract the charset encoding from the configured content type and // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this. String charSetEnc = null; try { if (contentType != null) { charSetEnc = new ContentType(contentType).getParameter("charset"); } } catch (ParseException ex) { // ignore } msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); } // if the content type was not found, but the service defined it.. use it if (contentType == null) { if (entry.getContentType() != null) { contentType = entry.getContentType(); } else if (VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE) != null) { contentType = VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE); } } // does the service specify a default reply file URI ? String replyFileURI = entry.getReplyFileURI(); if (replyFileURI != null) { msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, new VFSOutTransportInfo(replyFileURI, entry.isFileLockingEnabled())); } // Determine the message builder to use Builder builder; if (contentType == null) { log.debug("No content type specified. Using SOAP builder."); builder = new SOAPBuilder(); } else { int index = contentType.indexOf(';'); String type = index > 0 ? contentType.substring(0, index) : contentType; builder = BuilderUtil.getBuilderFromSelector(type, msgContext); if (builder == null) { if (log.isDebugEnabled()) { log.debug("No message builder found for type '" + type + "'. Falling back to SOAP."); } builder = new SOAPBuilder(); } } // set the message payload to the message context InputStream in; ManagedDataSource dataSource; if (builder instanceof DataSourceMessageBuilder && entry.isStreaming()) { in = null; dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType)); } else { in = new AutoCloseInputStream(content.getInputStream()); dataSource = null; } try { OMElement documentElement; if (in != null) { documentElement = builder.processDocument(in, contentType, msgContext); } else { documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType, msgContext); } msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement)); handleIncomingMessage(msgContext, transportHeaders, null, //* SOAP Action - not applicable *// contentType); } finally { if (dataSource != null) { dataSource.destroy(); } } if (log.isDebugEnabled()) { log.debug("Processed file : " + VFSUtils.maskURLPassword(file.toString()) + " of Content-type : " + contentType); } } catch (FileSystemException e) { handleException( "Error reading file content or attributes : " + VFSUtils.maskURLPassword(file.toString()), e); } finally { try { if (file != null) { file.close(); } } catch (FileSystemException warn) { // ignore the warning, since we handed over the stream close job to // AutocloseInputstream.. } } }
From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java
@Override public DownloadFile getFile(String dir, SharedUserPortletParameters userParameters) { try {//from www . java2 s . c o m FileObject file = cd(dir, userParameters); FileContent fc = file.getContent(); int size = new Long(fc.getSize()).intValue(); String baseName = fc.getFile().getName().getBaseName(); // fc.getContentInfo().getContentType() use URLConnection.getFileNameMap, // we prefer here to use our getMimeType : for Excel files and co // String contentType = fc.getContentInfo().getContentType(); String contentType = JsTreeFile.getMimeType(baseName.toLowerCase()); InputStream inputStream = fc.getInputStream(); DownloadFile dlFile = new DownloadFile(contentType, size, baseName, inputStream); return dlFile; } catch (FileSystemException e) { log.warn("can't download file : " + e.getMessage(), e); } return null; }
From source file:org.fuin.vfs2.filter.EmptyFileFilter.java
/** * Checks to see if the file is empty. A non-existing file is also * considered empty./*from w w w .java 2 s . c o m*/ * * @param fileInfo * the file or directory to check * * @return {@code true} if the file or directory is <i>empty</i>, otherwise * {@code false}. */ @Override public boolean accept(final FileSelectInfo fileInfo) { final FileObject file = fileInfo.getFile(); try { if (!file.exists()) { return true; } if (file.getType() == FileType.FOLDER) { final FileObject[] files = file.getChildren(); return files == null || files.length == 0; } final FileContent content = file.getContent(); try { return content.getSize() == 0; } finally { content.close(); } } catch (final FileSystemException ex) { throw new RuntimeException(ex); } }
From source file:org.fuin.vfs2.filter.SizeFileFilter.java
/** * Checks to see if the size of the file is favorable. * <p>/* w w w. j av a 2 s .c o m*/ * If size equals threshold and smaller files are required, file <b>IS * NOT</b> selected. If size equals threshold and larger files are required, * file <b>IS</b> selected. * <p> * Non-existing files return always false (will never be accepted). * * @param fileInfo * the File to check * * @return true if the filename matches */ @Override public boolean accept(final FileSelectInfo fileInfo) { try { final FileObject file = fileInfo.getFile(); if (!file.exists()) { return false; } final FileContent content = file.getContent(); try { final long length = content.getSize(); final boolean smaller = length < size; return acceptLarger ? !smaller : smaller; } finally { content.close(); } } catch (final FileSystemException ex) { throw new RuntimeException(ex); } }
From source file:org.mycore.common.content.MCRVFSContent.java
@Override public long length() throws IOException { FileContent content = fo.getContent(); try {//from w w w . j ava 2s. c o m return content.getSize(); } finally { fo.close(); } }
From source file:org.mycore.common.content.MCRVFSContent.java
@Override public String getETag() throws IOException { FileContent content = fo.getContent(); try {/* www.j a va 2 s.c o m*/ String systemId = getSystemId(); if (systemId == null) { systemId = fo.getName().getURI(); } long length = content.getSize(); long lastModified = content.getLastModifiedTime(); String eTag = getSimpleWeakETag(systemId, length, lastModified); if (eTag == null) { return null; } return eTag.substring(2); //remove weak } finally { content.close(); } }