List of usage examples for org.apache.commons.vfs2 FileObject getContent
FileContent getContent() throws FileSystemException;
From source file:maspack.fileutil.FileCacher.java
public InputStream getInputStream(URIx uri) throws FileSystemException { FileObject remoteFile = null; // will resolve next // loop through authenticators until we either succeed or cancel boolean cancel = false; while (remoteFile == null && cancel == false) { remoteFile = resolveRemote(uri); }/*w w w.j a v a 2s.c o m*/ if (remoteFile == null || !remoteFile.exists()) { throw new FileSystemException("Cannot find remote file <" + uri.toString() + ">", new FileNotFoundException("<" + uri.toString() + ">")); } // open stream content InputStream stream = null; try { stream = remoteFile.getContent().getInputStream(); } catch (Exception e) { remoteFile.close(); throw new RuntimeException("Failed to open " + remoteFile.getURL(), e); } finally { } return stream; }
From source file:com.google.code.docbook4j.renderer.FORenderer.java
@Override protected FileObject postProcess(final FileObject xmlSource, final FileObject xslSource, final FileObject xsltResult, final FileObject userConfigXml) throws Docbook4JException { FileObject target = null; try {/* www . j av a2s .c o m*/ final FopFactory fopFactory = FopFactory.newInstance(); final FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.setBaseURL(xmlSource.getParent().getURL().toExternalForm()); userAgent.setURIResolver(new VfsURIResolver()); enhanceFOUserAgent(userAgent); String tmpPdf = "tmp://" + UUID.randomUUID().toString(); target = FileObjectUtils.resolveFile(tmpPdf); target.createFile(); Configuration configuration = createFOPConfig(userConfigXml); if (configuration != null) { fopFactory.setUserConfig(configuration); fopFactory.setBaseURL(userConfigXml.getParent().getURL().toExternalForm()); fopFactory.setFontBaseURL(userConfigXml.getParent().getURL().toExternalForm()); } Fop fop = fopFactory.newFop(getMimeType(), userAgent, target.getContent().getOutputStream()); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // identity // transformer transformer.setParameter("use.extensions", "1"); transformer.setParameter("fop.extensions", "0"); transformer.setParameter("fop1.extensions", "1"); Source src = new StreamSource(xsltResult.getContent().getInputStream()); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); return target; } catch (FileSystemException e) { throw new Docbook4JException("Error create filesystem manager!", e); } catch (TransformerException e) { throw new Docbook4JException("Error transforming fo to pdf!", e); } catch (FOPException e) { throw new Docbook4JException("Error transforming fo to pdf!", e); } catch (ConfigurationException e) { throw new Docbook4JException("Error loading user configuration!", e); } catch (SAXException e) { throw new Docbook4JException("Error loading user configuration!", e); } catch (IOException e) { throw new Docbook4JException("Error loading user configuration!", e); } finally { FileObjectUtils.closeFileObjectQuietly(target); } }
From source file:de.unioninvestment.portal.explorer.view.vfs.TableView.java
public void attach() { selectedDir = cb.getVfsUrl();/*from w w w. j a v a 2 s . co m*/ try { final VFSFileExplorerPortlet app = instance; final User user = (User) app.getUser(); final FileSystemManager fFileSystemManager = fileSystemManager; final FileSystemOptions fOpts = opts; final Table table = new Table() { private static final long serialVersionUID = 1L; protected String formatPropertyValue(Object rowId, Object colId, Property property) { if (TABLE_PROP_FILE_NAME.equals(colId)) { if (property != null && property.getValue() != null) { return getDisplayPath(property.getValue().toString()); } } if (TABLE_PROP_FILE_DATE.equals(colId)) { if (property != null && property.getValue() != null) { SimpleDateFormat sdf = new SimpleDateFormat("dd.MMM yyyy HH:mm:ss"); return sdf.format((Date) property.getValue()); } } return super.formatPropertyValue(rowId, colId, property); } }; table.setSizeFull(); table.setMultiSelect(true); table.setSelectable(true); table.setImmediate(true); table.addContainerProperty(TABLE_PROP_FILE_NAME, String.class, null); table.addContainerProperty(TABLE_PROP_FILE_SIZE, Long.class, null); table.addContainerProperty(TABLE_PROP_FILE_DATE, Date.class, null); if (app != null) { app.getEventBus().addHandler(TableChangedEvent.class, new TableChangedEventHandler() { private static final long serialVersionUID = 1L; @Override public void onValueChanged(TableChangedEvent event) { try { selectedDir = event.getNewDirectory(); fillTableData(event.getNewDirectory(), table, fFileSystemManager, fOpts, null); } catch (IOException e) { e.printStackTrace(); } } }); } table.addListener(new Table.ValueChangeListener() { private static final long serialVersionUID = 1L; public void valueChange(ValueChangeEvent event) { Set<?> value = (Set<?>) event.getProperty().getValue(); if (null == value || value.size() == 0) { markedRows = null; } else { markedRows = value; } } }); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); Button btDownload = new Button("Download File(s)"); btDownload.addListener(new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { if (markedRows == null || markedRows.size() == 0) getWindow().showNotification("No Files selected !", Window.Notification.TYPE_WARNING_MESSAGE); else { String[] files = new String[markedRows.size()]; int fileCount = 0; for (Object item : markedRows) { Item it = table.getItem(item); files[fileCount] = it.getItemProperty(TABLE_PROP_FILE_NAME).toString(); fileCount++; } File dlFile = null; if (fileCount == 1) { try { String fileName = files[0]; dlFile = getFileFromVFSObject(fFileSystemManager, fOpts, fileName); logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by " + user.getScreenName()); } catch (Exception e) { e.printStackTrace(); } } else { byte[] buf = new byte[1024]; try { dlFile = File.createTempFile("Files", ".zip"); ZipOutputStream out = new ZipOutputStream( new FileOutputStream(dlFile.getAbsolutePath())); for (int i = 0; i < files.length; i++) { String fileName = files[i]; logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by " + user.getScreenName()); File f = getFileFromVFSObject(fFileSystemManager, fOpts, fileName); FileInputStream in = new FileInputStream(f); out.putNextEntry(new ZipEntry(f.getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); } catch (IOException e) { } } if (dlFile != null) { try { DownloadResource downloadResource = new DownloadResource(dlFile, getApplication()); getApplication().getMainWindow().open(downloadResource, "_new"); } catch (FileNotFoundException e) { getWindow().showNotification("File not found !", Window.Notification.TYPE_ERROR_MESSAGE); e.printStackTrace(); } } if (dlFile != null) { dlFile.delete(); } } } }); Button btDelete = new Button("Delete File(s)"); btDelete.addListener(new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { if (markedRows == null || markedRows.size() == 0) getWindow().showNotification("No Files selected !", Window.Notification.TYPE_WARNING_MESSAGE); else { for (Object item : markedRows) { Item it = table.getItem(item); String fileToDelete = it.getItemProperty(TABLE_PROP_FILE_NAME).toString(); logger.log(Level.INFO, "Delete File " + fileToDelete); try { FileObject delFile = fFileSystemManager.resolveFile(fileToDelete, fOpts); logger.log(Level.INFO, "vfs2portlet: delete file " + delFile.getName() + " by " + user.getScreenName()); boolean b = delFile.delete(); if (b) logger.log(Level.INFO, "delete ok"); else logger.log(Level.INFO, "delete failed"); } catch (FileSystemException e) { e.printStackTrace(); } } try { fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } catch (IOException e) { e.printStackTrace(); } } } }); Button selAll = new Button("Select All", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { table.setValue(table.getItemIds()); } }); Button selNone = new Button("Select None", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { table.setValue(null); } }); final UploadReceiver receiver = new UploadReceiver(); upload = new Upload(null, receiver); upload.setImmediate(true); upload.setButtonCaption("File Upload"); upload.addListener((new Upload.SucceededListener() { private static final long serialVersionUID = 1L; public void uploadSucceeded(SucceededEvent event) { try { String fileName = receiver.getFileName(); ByteArrayOutputStream bos = receiver.getUploadedFile(); byte[] buf = bos.toByteArray(); ByteArrayInputStream bis = new ByteArrayInputStream(buf); String fileToAdd = selectedDir + "/" + fileName; logger.log(Level.INFO, "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName()); FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts); localFile.createFile(); OutputStream localOutputStream = localFile.getContent().getOutputStream(); IOUtils.copy(bis, localOutputStream); localOutputStream.flush(); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); app.getMainWindow().showNotification("Upload " + fileName + " successful ! ", Notification.TYPE_TRAY_NOTIFICATION); } catch (Exception e) { e.printStackTrace(); } } })); upload.addListener(new Upload.FailedListener() { private static final long serialVersionUID = 1L; public void uploadFailed(FailedEvent event) { System.out.println("Upload failed ! "); } }); multiFileUpload = new MultiFileUpload() { private static final long serialVersionUID = 1L; protected void handleFile(File file, String fileName, String mimeType, long length) { try { byte[] buf = FileUtils.readFileToByteArray(file); ByteArrayInputStream bis = new ByteArrayInputStream(buf); String fileToAdd = selectedDir + "/" + fileName; logger.log(Level.INFO, "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName()); FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts); localFile.createFile(); OutputStream localOutputStream = localFile.getContent().getOutputStream(); IOUtils.copy(bis, localOutputStream); localOutputStream.flush(); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } catch (FileSystemException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } protected FileBuffer createReceiver() { FileBuffer receiver = super.createReceiver(); /* * Make receiver not to delete files after they have been * handled by #handleFile(). */ receiver.setDeleteFiles(false); return receiver; } }; multiFileUpload.setUploadButtonCaption("Upload File(s)"); HorizontalLayout filterGrp = new HorizontalLayout(); filterGrp.setSpacing(true); final TextField tfFilter = new TextField(); Button btFileFilter = new Button("Filter", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { String filterVal = (String) tfFilter.getValue(); try { if (filterVal == null || filterVal.length() == 0) { fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } else { fillTableData(selectedDir, table, fFileSystemManager, fOpts, filterVal); } } catch (IOException e) { e.printStackTrace(); } } }); Button btResetFileFilter = new Button("Reset", new Button.ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(Button.ClickEvent event) { try { tfFilter.setValue(""); fillTableData(selectedDir, table, fFileSystemManager, fOpts, null); } catch (ReadOnlyException e) { e.printStackTrace(); } catch (ConversionException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); filterGrp.addComponent(tfFilter); filterGrp.addComponent(btFileFilter); filterGrp.addComponent(btResetFileFilter); addComponent(filterGrp); addComponent(table); HorizontalLayout btGrp = new HorizontalLayout(); btGrp.setSpacing(true); btGrp.addComponent(selAll); btGrp.setComponentAlignment(selAll, Alignment.MIDDLE_CENTER); btGrp.addComponent(selNone); btGrp.setComponentAlignment(selNone, Alignment.MIDDLE_CENTER); btGrp.addComponent(btDownload); btGrp.setComponentAlignment(btDownload, Alignment.MIDDLE_CENTER); List<Role> roles = null; boolean matchUserRole = false; try { if (user != null) { roles = user.getRoles(); } } catch (SystemException e) { e.printStackTrace(); } if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() == 0) { btGrp.addComponent(btDelete); btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER); } else if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() > 0) { matchUserRole = isUserInRole(roles, cb.getDeleteRoles()); if (matchUserRole) { btGrp.addComponent(btDelete); btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER); } } if (cb.isUploadEnabled() && cb.getUploadRoles().length() == 0) { btGrp.addComponent(upload); btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER); btGrp.addComponent(multiFileUpload); btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER); } else if (cb.isUploadEnabled() && cb.getUploadRoles().length() > 0) { matchUserRole = isUserInRole(roles, cb.getUploadRoles()); if (matchUserRole) { btGrp.addComponent(upload); btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER); btGrp.addComponent(multiFileUpload); btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER); } } addComponent(btGrp); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.sonicle.webtop.mail.MultipartIterator.java
/** * Creates a file on disk from the current mulitpart element * @param fileName the name of the multipart file *//*from w ww. ja v a 2 s. c o m*/ protected FileObject createVFSFile(String filename) throws IOException { FileObject vfsfile = fileObjectDir.resolveFile(filename); int n = 0; String xfilename = filename; String xext = null; int ix = xfilename.lastIndexOf("."); if (ix > 0) { xext = xfilename.substring(ix + 1); xfilename = xfilename.substring(0, ix); } while (vfsfile.exists()) { ++n; filename = xfilename + " (" + n + ")"; if (xext != null) filename += "." + xext; vfsfile = fileObjectDir.resolveFile(filename); } OutputStream fos = vfsfile.getContent().getOutputStream(); try { writeStream(fos); } catch (IOException exc) { vfsfile.delete(); } return vfsfile; }
From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignProvider.java
private static boolean performChange(ChangedDocument changedDocument, FileSystemDesignProvider originalDesignProvider, OverlayStatus status, String targetEncoding, FileObject baseFolder, Logger log, DesignFileValidator validator) throws FileSystemException, NoSuchAlgorithmException, UnsupportedEncodingException, IOException, WGDesignSyncException { boolean conflictFileCreated = false; log.info("Updating overlay resource " + changedDocument.getDocumentKey()); // Find files which represent the document in source and target FileObject sourceDocFile = originalDesignProvider.getBaseFolder() .resolveFile(changedDocument.getSourceFilePath()); FileObject targetDocFile = baseFolder.resolveFile(changedDocument.getTargetFilePath()); // Collect files to copy and delete Map<FileObject, FileObject> filesToCopy = new HashMap<FileObject, FileObject>(); List<FileObject> filesToDelete = new ArrayList<FileObject>(); // Collect for file containers: Must traverse container content if (changedDocument.getDocumentKey().getDocType() == WGDocument.TYPE_FILECONTAINER) { if (changedDocument.getChangeType() == ChangeType.NEW) { targetDocFile.createFolder(); }//w w w. j ava 2s . c o m // Copy all files in container from the source to the target for (FileObject sourceFile : sourceDocFile.getChildren()) { if (sourceFile.getType().equals(FileType.FILE)) { if (!isValidDesignFile(sourceFile, validator)) { continue; } filesToCopy.put(sourceFile, targetDocFile.resolveFile(sourceFile.getName().getBaseName())); } } // Delete all files in target that were deployed with previous base version but are deleted in current base version for (FileObject targetFile : targetDocFile.getChildren()) { if (targetFile.getType().equals(FileType.FILE)) { if (!isValidDesignFile(targetFile, validator)) { continue; } FileObject sourceFile = sourceDocFile.resolveFile(targetFile.getName().getBaseName()); if (sourceFile.exists()) { continue; } // Only delete those that were deployed with previous base version and have unaltered content String resourcePath = baseFolder.getName().getRelativeName(targetFile.getName()); ResourceData resourceData = status.getOverlayData().getOverlayResources().get(resourcePath); if (resourceData != null) { String hash = MD5HashingInputStream.getStreamHash(targetFile.getContent().getInputStream()); if (resourceData.getMd5Hash().equals(hash)) { filesToDelete.add(targetFile); } } } } } // Collect for anything else else { filesToCopy.put(sourceDocFile, targetDocFile); } // Copy files for (Map.Entry<FileObject, FileObject> files : filesToCopy.entrySet()) { FileObject sourceFile = files.getKey(); FileObject targetFile = files.getValue(); String resourcePath = baseFolder.getName().getRelativeName(targetFile.getName()); if (changedDocument.getChangeType() == ChangeType.CONFLICT) { // Do a test if the current file is conflicting. If so we write to a conflict file instead InputStream in = new BufferedInputStream(sourceFile.getContent().getInputStream()); String currentHash = MD5HashingInputStream.getStreamHash(in); ResourceData deployedHash = status.getOverlayData().getOverlayResources().get(resourcePath); boolean skipConflict = false; // Conflict on file container: A single file might just be missing in the target. We can safely copy that to the target without treating as conflict (#00002440) if (deployedHash == null && changedDocument.getDocumentKey().getDocType() == WGDocument.TYPE_FILECONTAINER && !targetFile.exists()) { skipConflict = true; } if (!skipConflict && (deployedHash == null || !deployedHash.getMd5Hash().equals(currentHash))) { targetFile = createConflictFile(targetFile); conflictFileCreated = true; log.warn("Modified overlay resource " + resourcePath + " is updated in base design. We write the updated base version to conflict file for manual resolution: " + baseFolder.getName().getRelativeName(targetFile.getName())); } } // Write file InputStream in = new BufferedInputStream(sourceFile.getContent().getInputStream()); MD5HashingOutputStream out = new MD5HashingOutputStream( new BufferedOutputStream(targetFile.getContent().getOutputStream(false))); // Update resource data resourceInToOut(in, originalDesignProvider.getFileEncoding(), out, targetEncoding); OverlayData.ResourceData resourceData = new OverlayData.ResourceData(); resourceData.setMd5Hash(out.getHash()); status.getOverlayData().setOverlayResource(resourcePath, resourceData); } // Delete files for (FileObject fileToDelete : filesToDelete) { String resourcePath = baseFolder.getName().getRelativeName(fileToDelete.getName()); fileToDelete.delete(); status.getOverlayData().removeOverlayResource(resourcePath); } return conflictFileCreated; }
From source file:fr.cls.atoll.motu.library.misc.vfs.VFSManager.java
/** * Gets the uri as input stream./*w w w.java 2 s . com*/ * * @param uri the uri * * @return the uri as input stream * * @throws MotuException the motu exception */ public InputStream getUriAsInputStream(String uri) throws MotuException { if (LOG.isDebugEnabled()) { LOG.debug("getUriAsInputStream(String) - entering"); } InputStream in = null; try { FileObject fileObject = resolveFile(uri); if (fileObject != null) { in = fileObject.getContent().getInputStream(); } } catch (IOException e) { LOG.error("getUriAsInputStream(String)", e); throw new MotuException(String.format("'%s' uri file has not be found", uri), e); } if (LOG.isDebugEnabled()) { LOG.debug("getUriAsInputStream(String) - exiting"); } return in; }
From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignManager.java
private Writer createWriter(FileObject file) throws IOException { return new OutputStreamWriter(file.getContent().getOutputStream(), getFileEncoding()); }
From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignManager.java
protected void updateConfiguration() throws IOException, WGDesignSyncException, FileSystemException, InvalidCSConfigVersionException { boolean configUpdated = false; // Import config files FileObject designFile = getSyncInfoFile(); long currentDesignFileTimestamp = designFile.getContent().getLastModifiedTime(); if (_designFileTimestamp == null || currentDesignFileTimestamp > _designFileTimestamp.longValue()) { _designFileTimestamp = new Long(currentDesignFileTimestamp); importSyncInfo(designFile);//from www .jav a 2s . c om configUpdated = true; } FileObject csconfigFile = getFilesFolder().resolveFile("system/csconfig.xml"); if (csconfigFile.exists()) { long currentCsconfigTimestamp = csconfigFile.getContent().getLastModifiedTime(); if (_csconfigTimestamp == null || currentCsconfigTimestamp > _csconfigTimestamp.longValue()) { _csconfigTimestamp = new Long(currentCsconfigTimestamp); importCSConfig(csconfigFile); configUpdated = true; } } // Load configuration settings if (configUpdated) { determineDesignEncoding(); determineEncryption(); determineSyncDefaults(); } }
From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java
public void updateFSDesignResource(RemoteSession session, String path, DataSource content, long lastModified) throws WGAServiceException { if (!isAdminServiceEnabled()) { throw new WGAServiceException("Administrative services are disabled"); }// w w w . ja va 2s. co m if (!isAdminSession(session)) { throw new WGAServiceException("You need an administrative login to access this service."); } WGADesignSource source = _core.getDesignManager().getDesignSources() .get(WGAConfiguration.UID_DESIGNSOURCE_FILESYSTEM); if (source instanceof FileSystemDesignSource) { FileSystemDesignSource fsSource = (FileSystemDesignSource) source; try { fsSource.getDir().refresh(); FileObject resource = fsSource.getDir().resolveFile(path); String basePath = fsSource.getDir().getURL().getPath(); String resourcePath = resource.getURL().getPath(); if (!resourcePath.startsWith(basePath)) { throw new WGAServiceException( new IllegalArgumentException("Illegal design resource path '" + path + "'.")); } resource.createFile(); OutputStream out = resource.getContent().getOutputStream(); InputStream in = content.getInputStream(); WGUtils.inToOut(in, out, 1024); out.close(); in.close(); resource.getContent().setLastModifiedTime(lastModified); clearDesignFileCache(fsSource, fsSource.getDir().getName().getRelativeName(resource.getName())); } catch (FileSystemException e) { // throw new WGAServiceException("Updating FSDesignResource '" + path + "' failed.", e); } catch (IOException e) { throw new WGAServiceException("Updating FSDesignResource '" + path + "' failed.", e); } } }
From source file:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java
protected String readCode(DesignMetadata md) throws FileNotFoundException, IOException, WGDesignSyncException, InstantiationException, IllegalAccessException { // No, filecontainers have no code, but thanks for asking.... if (getType() == WGDocument.TYPE_FILECONTAINER) { return null; }//from w w w. j a v a2 s . co m FileObject codeFile = getCodeFile(); if (!codeFile.exists()) { throw new WGDesignSyncException("Code of file '" + getCodeFile().getName().getPath() + "' could not be read because the file does not exist."); } LineNumberReader reader = new LineNumberReader(createReader(codeFile)); StringWriter writer = new StringWriter(); int headerLines = 0; try { String line; boolean lookForHeaders = true; boolean firstLine = true; while ((line = reader.readLine()) != null) { if (lookForHeaders == true && line.startsWith("##")) { processDesignHeader(line, md.getInfo()); headerLines++; } else { lookForHeaders = false; if (!firstLine) { writer.write("\n"); } else { firstLine = false; } writer.write(line); } } } finally { reader.close(); codeFile.getContent().close(); } writer.close(); md.setHeaderLines(headerLines); String code = writer.toString(); return code; }