List of usage examples for org.apache.commons.vfs FileObject getName
public FileName getName();
From source file:org.docx4all.ui.menu.HyperlinkMenu.java
public void openLinkedDocument(FileObject sourceFile, HyperlinkML linkML, boolean autoCreateLinkedDocument) { if (autoCreateLinkedDocument && linkML.getWordprocessingMLPackage() == null) { throw new IllegalArgumentException("Invalid HyperlinkML parameter"); }/*from ww w. j ava 2s.c o m*/ final WordMLEditor editor = WordMLEditor.getInstance(WordMLEditor.class); final ResourceMap rm = editor.getContext().getResourceMap(getClass()); String title = rm.getString(OPEN_LINKED_DOCUMENT_ACTION_NAME + ".Action.text"); String errMsg = null; String targetFilePath = HyperlinkML.encodeTarget(linkML, sourceFile, false); if (targetFilePath.startsWith("file://")) { // local file try { FileObject fo = VFSUtils.getFileSystemManager().resolveFile(targetFilePath); if (!fo.exists()) { if (autoCreateLinkedDocument) { boolean success = createInFileSystem(fo, linkML.getWordprocessingMLPackage()); if (!success) { // needs not display additional error message. fo = null; } } else { fo = null; errMsg = rm.getString(OPEN_LINKED_DOCUMENT_ACTION_NAME + ".file.not.found.message", targetFilePath); } } if (fo != null) { editor.createInternalFrame(fo); final String sourceUri = sourceFile.getName().getURI(); final String targetUri = fo.getName().getURI(); SwingUtilities.invokeLater(new Runnable() { public void run() { editor.tileLayout(sourceUri, targetUri); } }); } } catch (FileSystemException exc) { exc.printStackTrace(); errMsg = rm.getString(OPEN_LINKED_DOCUMENT_ACTION_NAME + ".io.error.message", targetFilePath); } } else if (targetFilePath.startsWith("webdav://")) { try { boolean recordAsLastOpenUrl = false; WordprocessingMLPackage newPackage = createNewEmptyPackage(linkML.getWordprocessingMLPackage()); if (autoCreateLinkedDocument && newPackage == null) { //cannot create a new WordprocessingMLPackage. //This is an unlikely situation. //Avoid creating new linked document. //TODO: probably display a message ? autoCreateLinkedDocument = false; } FileObject fo = openWebdavDocument(targetFilePath, recordAsLastOpenUrl, autoCreateLinkedDocument, newPackage, OPEN_LINKED_DOCUMENT_ACTION_NAME); if (fo != null) { final String sourceUri = sourceFile.getName().getURI(); final String targetUri = fo.getName().getURI(); SwingUtilities.invokeLater(new Runnable() { public void run() { editor.tileLayout(sourceUri, targetUri); } }); } else { //Does not need to display additional error message. //openWebdavDocument() must have displayed all necessary //messages. } } catch (FileSystemException exc) { exc.printStackTrace(); errMsg = rm.getString(OPEN_LINKED_DOCUMENT_ACTION_NAME + ".io.error.message", targetFilePath); } } else { errMsg = rm.getString(OPEN_LINKED_DOCUMENT_ACTION_NAME + ".unsupported.protocol.message", targetFilePath); } if (errMsg != null) { editor.showMessageDialog(title, errMsg, JOptionPane.ERROR_MESSAGE); } }
From source file:org.docx4all.ui.menu.HyperlinkMenu.java
/** * Opens a webdav document pointed by vfsWebdavUrl parameter in its own * internal frame.//w w w . j a v a2 s.co m * * vfsWebdavUrl is a VFS Webdav URL that points to a webdav document. * It may or may not contain user credentials information. * For example: * <> webdav://dev.plutext.org/alfresco/plutextwebdav/User Homes/someone/AFile.docx * <> webdav://dev.plutext.org:80/alfresco/plutextwebdav/User Homes/someone/AFile.docx * <> webdav://username:password@dev.plutext.org/alfresco/plutextwebdav/User Homes/someone/AFile.docx * * In the event that vfsWebdavUrl does not have user credentials or its user credentials * is invalid then this method will cycle through each known user credential found in * VFSJFileChooser Bookmark in order to find an authorised user. If no such user can be * found then an authentication challenge dialog will be displayed and user has three * attempts to authenticate himself. * * @param vfsWebdavUrl a VFS Webdav Url in its friendly format. * @param recordAsLastOpenUrl a boolean flag that indicates whether vfsWebdavUrl * should be recorded as the last open url. * @param createNewIfNotFound a boolean flag that indicates whether a new webdav * document at vfsWebdavUrl should be created if it has not existed. * @param newPackage a WordprocessingMLPackage that will become the content of * newly created webdav document. This parameter must be supplied when * createNewIfNotFound parameter is true. * @param callerActionName an Action name that can be used as a key to get * resource properties in relation to dialog messages. * @return FileObject of the opened document */ public FileObject openWebdavDocument(String vfsWebdavUrl, boolean recordAsLastOpenUrl, boolean createNewIfNotFound, WordprocessingMLPackage newPackage, String callerActionName) { if (!vfsWebdavUrl.startsWith("webdav://")) { throw new IllegalArgumentException("Not a webdav uri"); } if (createNewIfNotFound && newPackage == null) { throw new IllegalArgumentException("Invalid newPackage parameter"); } final WordMLEditor editor = WordMLEditor.getInstance(WordMLEditor.class); final ResourceMap rm = editor.getContext().getResourceMap(getClass()); VFSURIParser uriParser = new VFSURIParser(vfsWebdavUrl, false); if (uriParser.getUsername() != null && uriParser.getUsername().length() > 0 && uriParser.getPassword() != null && uriParser.getPassword().length() > 0) { //vfsWebdavUrl has user credentials. try { FileObject fo = VFSUtils.getFileSystemManager().resolveFile(vfsWebdavUrl); if (fo.exists()) { if (recordAsLastOpenUrl) { Preferences prefs = Preferences.userNodeForPackage(FileMenu.class); String lastFileUri = fo.getName().getURI(); prefs.put(Constants.LAST_OPENED_FILE, lastFileUri); PreferenceUtil.flush(prefs); } log.info("\n\n Opening " + fo.getName().getURI()); editor.createInternalFrame(fo); return fo; } } catch (FileSystemException exc) { ; } } String temp = rm.getString(Constants.VFSJFILECHOOSER_DEFAULT_WEBDAV_FOLDER_BOOKMARK_NAME); if (temp == null || temp.length() == 0) { temp = "Default Webdav Folder"; } else { temp = temp.trim(); } List<String> userCredentials = org.docx4all.vfs.VFSUtil.collectUserCredentialsFromBookmark(uriParser, temp); StringBuilder sb = new StringBuilder(); sb.append(uriParser.getHostname()); if (uriParser.getPortnumber() != null && uriParser.getPortnumber().length() > 0) { sb.append(":"); sb.append(uriParser.getPortnumber()); } sb.append(uriParser.getPath()); temp = sb.toString();//hostname[:port] and path vfsWebdavUrl = "webdav://" + temp; //Try each known userCredential to resolve a FileObject FileObject theFile = null; for (String uc : userCredentials) { sb.delete(0, sb.length()); sb.append("webdav://"); sb.append(uc); sb.append("@"); sb.append(temp); try { theFile = VFSUtils.getFileSystemManager().resolveFile(sb.toString()); if (theFile.exists()) { break; } else { theFile = null; } } catch (FileSystemException exc) { theFile = null; } } if (theFile != null) { //theFile exists if (recordAsLastOpenUrl) { Preferences prefs = Preferences.userNodeForPackage(FileMenu.class); String lastFileUri = theFile.getName().getURI(); prefs.put(Constants.LAST_OPENED_FILE, lastFileUri); PreferenceUtil.flush(prefs); } log.info("\n\n Opening " + theFile.getName().getURI()); editor.createInternalFrame(theFile); } else { //Cannot get theFile yet. //Get user to authenticate himself. String title = rm.getString(callerActionName + ".Action.text"); String errMsg = null; Preferences prefs = Preferences.userNodeForPackage(FileMenu.class); try { theFile = AuthenticationUtil.userAuthenticationChallenge(editor, vfsWebdavUrl, title); if (theFile == null) { //user may have cancelled the authentication challenge //or unsuccessfully authenticated himself. //Because AuthenticationUtil.userAuthenticationChallenge() //has displayed authentication failure message, we do //not need to do anything here. } else if (theFile.exists()) { String lastFileUri = theFile.getName().getURI(); if (recordAsLastOpenUrl) { prefs.put(Constants.LAST_OPENED_FILE, lastFileUri); } //Record lastFileUri in bookmark. //Use file name as bookmark entry title. int idx = lastFileUri.lastIndexOf("/"); org.docx4all.vfs.VFSUtil.addBookmarkEntry(lastFileUri.substring(idx + 1), new VFSURIParser(lastFileUri, false)); log.info("\n\n Opening " + lastFileUri); editor.createInternalFrame(theFile); } else if (createNewIfNotFound) { boolean success = createInFileSystem(theFile, newPackage); if (success) { String lastFileUri = theFile.getName().getURI(); if (recordAsLastOpenUrl) { prefs.put(Constants.LAST_OPENED_FILE, lastFileUri); } //Record lastFileUri in bookmark. //Use file name as bookmark entry title. int idx = lastFileUri.lastIndexOf("/"); org.docx4all.vfs.VFSUtil.addBookmarkEntry(lastFileUri.substring(idx + 1), new VFSURIParser(lastFileUri, false)); log.info("\n\n Opening " + lastFileUri); editor.createInternalFrame(theFile); } else { theFile = null; errMsg = rm.getString(callerActionName + ".file.io.error.message", vfsWebdavUrl); } } else { theFile = null; errMsg = rm.getString(callerActionName + ".file.not.found.message", vfsWebdavUrl); } } catch (FileSystemException exc) { exc.printStackTrace(); theFile = null; errMsg = rm.getString(callerActionName + ".file.io.error.message", vfsWebdavUrl); } finally { PreferenceUtil.flush(prefs); } if (errMsg != null) { theFile = null; editor.showMessageDialog(title, errMsg, JOptionPane.ERROR_MESSAGE); } } return theFile; }
From source file:org.docx4all.vfs.FileNameExtensionFilter.java
/** * Whether the given file is accepted by this filter. * @param f/*from w w w . ja v a2 s . c om*/ * @return */ public boolean accept(FileObject f) { boolean isAccepted = false; if (f != null) { if (VFSUtils.isDirectory(f)) { isAccepted = true; } else { String fext = f.getName().getExtension().toLowerCase(); for (String extension : lowerCaseExtensions) { if (fext.equals(extension)) { isAccepted = true; break; } } } } return isAccepted; }
From source file:org.docx4all.xml.ElementMLFactory.java
public final static DocumentML createDocumentML(FileObject f, boolean applyFilter) throws IOException { if (f == null || !(Constants.DOCX_STRING.equalsIgnoreCase(f.getName().getExtension()) || Constants.FLAT_OPC_STRING.equalsIgnoreCase(f.getName().getExtension()))) { throw new IllegalArgumentException("Not a .docx (or .xml) file."); }//w w w .ja va2 s.c o m DocumentML docML = null; try { WordprocessingMLPackage wordMLPackage; if (Constants.DOCX_STRING.equalsIgnoreCase(f.getName().getExtension())) { // .docx LoadFromVFSZipFile loader = new LoadFromVFSZipFile(true); //LoadFromVFSZipFile.setCustomXmlDataStorageClass(new org.docx4j.model.datastorage.Dom4jCustomXmlDataStorage()); wordMLPackage = (WordprocessingMLPackage) loader.getPackageFromFileObject(f); } else { // .xml // First get the Flat OPC package from the File Object InputStream is = f.getContent().getInputStream(); Unmarshaller u = Context.jcXmlPackage.createUnmarshaller(); u.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler()); javax.xml.bind.JAXBElement j = (javax.xml.bind.JAXBElement) u.unmarshal(is); org.docx4j.xmlPackage.Package flatOpc = (org.docx4j.xmlPackage.Package) j.getValue(); System.out.println("unmarshalled "); // Now convert it to a docx4j WordML Package FlatOpcXmlImporter importer = new FlatOpcXmlImporter(flatOpc); wordMLPackage = (WordprocessingMLPackage) importer.get(); } if (applyFilter) { wordMLPackage = XmlUtil.applyFilter(wordMLPackage); } docML = new DocumentML(wordMLPackage); } catch (Docx4JException exc) { throw new IOException(exc); } catch (Exception exc) { throw new IOException(exc); } return docML; }
From source file:org.docx4all.xml.HyperlinkML.java
public final static String encodeTarget(HyperlinkML ml, FileObject sourceFile, boolean inFriendlyFormat) { String target = ml.getTarget(); if (target == null) { return null; }//from w ww .ja v a2 s .c o m target = target.replace('\\', '/'); int idx = target.indexOf("://"); if (idx > 0) { //if protocol is specified, directly construct //target by decoding it try { target = URLDecoder.decode(target, "UTF-8"); } catch (UnsupportedEncodingException exc) { //should not happen } if (inFriendlyFormat) { //target should already be in friendly format. } else if (sourceFile != null) { String sourcePath = sourceFile.getName().getURI(); if (sourcePath.startsWith("file://") || target.startsWith("file://")) { //either sourcePath or target is local. //No need for user credentials } else { VFSURIParser parser = new VFSURIParser(sourcePath, false); String username = parser.getUsername(); String password = parser.getPassword(); StringBuilder sb = new StringBuilder(); sb.append(target.substring(0, idx + 3)); sb.append(username); sb.append(":"); sb.append(password); sb.append("@"); sb.append(target.substring(idx + 3)); } } } else if (sourceFile != null) { //protocol is NOT specified in target. //Construct target by appending target to //sourceFile directory. String base = null; try { base = sourceFile.getParent().getName().getURI(); } catch (FileSystemException exc) { ;//ignore } if (base != null) { if (inFriendlyFormat) { base = VFSUtils.getFriendlyName(base, false); } StringBuilder sb = new StringBuilder(); sb.append(base.replace('\\', '/')); if (!base.endsWith("/")) { sb.append("/"); } if (target.startsWith("/")) { target = target.substring(1); } sb.append(target); target = sb.toString(); } } return target; }
From source file:org.docx4j.extras.vfs.LoadFromVFSZipFile.java
public OpcPackage getPackageFromFileObject(FileObject fo) throws Docx4JException { OpcPackage thePackage = null;/*from w w w .j av a 2s.co m*/ if (!(fo instanceof LocalFile)) { //Non-Local file such as webdav file. //We make a temporary local copy of the file. //TODO: 28/03/08 - This is a second approach of dealing with non-local file. //The first approach which is more preferable and done in SVN version 233 //does not create a temporary local copy of the file. //It uses Commons-VFS "zip://" uri scheme to directly access the non-local file. //This second approach is being carried out because the writing operation cannot //use Commons-VFS "zip://" scheme as the scheme does not support writing to //zip file yet. //TODO: 28/03/08 - DO NOT use "tmp://" scheme to make a temporary file. //as it is going to fail. The current Commons-VFS library is still buggy. StringBuffer sb = new StringBuffer("file:///"); sb.append(System.getProperty("user.home")); sb.append("/.docx4j/tmp/"); sb.append(fo.getName().getBaseName()); String tmpPath = sb.toString().replace('\\', '/'); LocalFile localCopy = null; try { localCopy = (LocalFile) VFS.getManager().resolveFile(tmpPath); localCopy.copyFrom(fo, new FileTypeSelector(FileType.FILE)); localCopy.close(); thePackage = getPackageFromLocalFile(localCopy); } catch (FileSystemException exc) { exc.printStackTrace(); throw new Docx4JException("Could not create a temporary local copy", exc); } finally { if (localCopy != null) { try { localCopy.delete(); } catch (FileSystemException exc) { exc.printStackTrace(); log.warn("Couldn't delete temporary file " + tmpPath); } } } } else { thePackage = getPackageFromLocalFile((LocalFile) fo); } return thePackage; }
From source file:org.docx4j.extras.vfs.VFSDoc.java
/** * @param in/* w ww . java2s . c om*/ * @return * @throws Exception */ public static WordprocessingMLPackage convert(org.apache.commons.vfs.FileObject in) throws Exception { LocalFile localCopy = null; if (!(in instanceof LocalFile)) { StringBuffer sb = new StringBuffer("file:///"); sb.append(System.getProperty("user.home")); sb.append("/.docx4j/tmp/"); sb.append(in.getName().getBaseName()); String tmpPath = sb.toString().replace('\\', '/'); try { localCopy = (LocalFile) VFS.getManager().resolveFile(tmpPath); localCopy.copyFrom(in, new FileTypeSelector(FileType.FILE)); localCopy.close(); } catch (FileSystemException exc) { exc.printStackTrace(); throw new Docx4JException("Could not create a temporary local copy", exc); } finally { if (localCopy != null) { try { localCopy.delete(); } catch (FileSystemException exc) { exc.printStackTrace(); log.warn("Couldn't delete temporary file " + tmpPath); } } } } else { localCopy = (LocalFile) in; } String localPath = VFSUtils.getLocalFilePath(in); if (localPath == null) { throw new Docx4JException("Couldn't get local path"); } return Doc.convert(new FileInputStream(localPath)); }
From source file:org.docx4j.extras.vfs.VFSUtils.java
/** * Returns the absolute path of Apache Commons-VFS FileObject if its uri scheme is 'file://' * This absolute path then can be used to construct java.io.File object. * /*from ww w .ja va 2 s. co m*/ * @param fo * @return local absolute path if any; * null, otherwise */ public final static String getLocalFilePath(org.apache.commons.vfs.FileObject fo) { String thePath = fo.getName().getURI(); String localScheme = "file://"; if (thePath.startsWith(localScheme)) { //uri syntax of local file system has this format "file:///[absoultePath]" try { int idx = localScheme.length(); if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") > -1) { //In Windows we're going to chop the leading "file:///" off. idx++; } thePath = thePath.substring(idx); thePath = UriParser.decode(thePath); } catch (FileSystemException exc) { exc.printStackTrace(); thePath = null; } } else { thePath = null; } return thePath; }
From source file:org.eclim.plugin.core.command.archive.ArchiveReadCommand.java
/** * {@inheritDoc}/*from ww w.ja va2 s. c o m*/ */ public String execute(CommandLine commandLine) throws Exception { InputStream in = null; OutputStream out = null; FileSystemManager fsManager = null; try { String file = commandLine.getValue(Options.FILE_OPTION); fsManager = VFS.getManager(); FileObject fileObject = fsManager.resolveFile(file); FileObject tempFile = fsManager .resolveFile(SystemUtils.JAVA_IO_TMPDIR + "/eclim/" + fileObject.getName().getPath()); // the vfs file cache isn't very intelligent, so clear it. fsManager.getFilesCache().clear(fileObject.getFileSystem()); fsManager.getFilesCache().clear(tempFile.getFileSystem()); // NOTE: FileObject.getName().getPath() does not include the drive // information. String path = tempFile.getName().getURI().substring(URI_PREFIX.length()); // account for windows uri which has an extra '/' in front of the drive // letter (file:///C:/blah/blah/blah). if (WIN_PATH.matcher(path).matches()) { path = path.substring(1); } //if(!tempFile.exists()){ tempFile.createFile(); in = fileObject.getContent().getInputStream(); out = tempFile.getContent().getOutputStream(); IOUtils.copy(in, out); new File(path).deleteOnExit(); //} return path; } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
From source file:org.eclim.plugin.jdt.util.JavaUtils.java
/** * Attempts to locate the IClassFile for the supplied file path from the * specified project's classpath.//from ww w . ja v a 2 s . co m * * @param project The project to find the class file in. * @param path Absolute path or url (jar:, zip:) to a .java source file. * @return The IClassFile. */ public static IClassFile findClassFile(IJavaProject project, String path) throws Exception { if (path.startsWith("/") || path.toLowerCase().startsWith("jar:") || path.toLowerCase().startsWith("zip:")) { FileSystemManager fsManager = VFS.getManager(); FileObject file = fsManager.resolveFile(path); if (file.exists()) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(file.getContent().getInputStream())); String pack = null; String line = null; while ((line = in.readLine()) != null) { Matcher matcher = PACKAGE_LINE.matcher(line); if (matcher.matches()) { pack = matcher.group(1); break; } } if (pack != null) { String name = pack + '.' + FileUtils.getFileName(file.getName().getPath()); IType type = project.findType(name); if (type != null) { return type.getClassFile(); } } } finally { IOUtils.closeQuietly(in); } } } return null; }