private IHyperlink openModule(Node current, ITextViewer textViewer, int offset) { while (current != null && !(current instanceof Element)) { current = current.getParentNode(); } if (current == null) { return null; } String pathUp = XmlUtils.pathUp(current, 2); if (!"modules/module".equals(pathUp)) { // $NON-NLS-1$ // just in case we are in some random plugin configuration snippet.. return null; } ITextFileBuffer buf = FileBuffers.getTextFileBufferManager().getTextFileBuffer(textViewer.getDocument()); if (buf == null) { // for repository based poms.. return null; } IFileStore folder = buf.getFileStore().getParent(); String path = XmlUtils.getTextValue(current); final String fPath = path; // construct IPath for the child pom file, handle relative paths.. while (folder != null && path.startsWith("../")) { // $NON-NLS-1$ folder = folder.getParent(); path = path.substring("../".length()); // $NON-NLS-1$ } if (folder == null) { return null; } IFileStore modulePom = folder.getChild(path); if (!modulePom.getName().endsWith("xml")) { // $NON-NLS-1$ modulePom = modulePom.getChild("pom.xml"); // $NON-NLS-1$ } final IFileStore fileStore = modulePom; if (!fileStore.fetchInfo().exists()) { return null; } assert current instanceof IndexedRegion; final IndexedRegion region = (IndexedRegion) current; return new IHyperlink() { public IRegion getHyperlinkRegion() { return new Region(region.getStartOffset(), region.getEndOffset() - region.getStartOffset()); } public String getHyperlinkText() { return NLS.bind(Messages.PomHyperlinkDetector_open_module, fPath); } public String getTypeLabel() { return "pom-module"; //$NON-NLS-1$ } public void open() { openXmlEditor(fileStore); } }; }
/** * Performs a git clone to a temporary location and then copies the files over top the already * generated project. This is because git cannot clone into an existing directory. * * @param monitor * @throws Exception */ protected void cloneAfter(IProgressMonitor monitor) throws Exception { SubMonitor sub = SubMonitor.convert(monitor, Messages.AbstractNewProjectWizard_CloningFromGitMsg, 100); // clone to tmp dir then copy files over top the project! File tmpFile = File.createTempFile("delete_me", "tmp"); // $NON-NLS-1$ //$NON-NLS-2$ File dest = new File(tmpFile.getParent(), "git_clone_tmp"); // $NON-NLS-1$ GitExecutable.instance() .clone( selectedTemplate.getLocation(), Path.fromOSString(dest.getAbsolutePath()), true, sub.newChild(85)); IFileStore tmpClone = EFS.getStore(dest.toURI()); // Wipe the .git folder before copying? Wipe the .project file before copying? IFileStore dotGit = tmpClone.getChild(".git"); // $NON-NLS-1$ dotGit.delete(EFS.NONE, sub.newChild(2)); IFileStore dotProject = tmpClone.getChild(IProjectDescription.DESCRIPTION_FILE_NAME); if (dotProject.fetchInfo().exists()) { dotProject.delete(EFS.NONE, sub.newChild(1)); } // OK, copy the cloned template's contents over IFileStore projectStore = EFS.getStore(newProject.getLocationURI()); tmpClone.copy(projectStore, EFS.OVERWRITE, sub.newChild(9)); // Now get rid of the temp clone! tmpClone.delete(EFS.NONE, sub.newChild(3)); sub.done(); }
private void openFile(File file, DotGraphView view) { if (view.currentFile == null) { // no workspace file for cur. graph IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path("")); // $NON-NLS-1$ fileStore = fileStore.getChild(file.getAbsolutePath()); if (!fileStore.fetchInfo().isDirectory() && fileStore.fetchInfo().exists()) { IWorkbenchPage page = view.getSite().getPage(); try { IDE.openEditorOnFileStore(page, fileStore); } catch (PartInitException e) { e.printStackTrace(); } } } else { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IPath location = Path.fromOSString(file.getAbsolutePath()); IFile copy = workspace.getRoot().getFileForLocation(location); IEditorRegistry registry = PlatformUI.getWorkbench().getEditorRegistry(); if (registry.isSystemExternalEditorAvailable(copy.getName())) { try { view.getViewSite() .getPage() .openEditor(new FileEditorInput(copy), IEditorRegistry.SYSTEM_EXTERNAL_EDITOR_ID); } catch (PartInitException e) { e.printStackTrace(); } } } }
/** Find out the name of the directory that fits better to this UUID. */ public IFileStore folderFor(UniversalUniqueIdentifier uuid) { byte hash = hashUUIDbytes(uuid); hash &= mask; // limit the range of the directory String dirName = Integer.toHexString(hash + (128 & mask)); // +(128 & mask) makes sure 00h is the lower value return localStore.getChild(dirName); }
private boolean handlePost( HttpServletRequest request, HttpServletResponse response, IFileStore dir) throws JSONException, CoreException, ServletException, IOException { // setup and precondition checks JSONObject requestObject = OrionServlet.readJSONRequest(request); String name = computeName(request, requestObject); if (name.length() == 0) return statusHandler.handleRequest( request, response, new ServerStatus( IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "File name not specified.", null)); int options = getCreateOptions(request); IFileStore toCreate = dir.getChild(name); boolean destinationExists = toCreate.fetchInfo().exists(); if (!validateOptions(request, response, toCreate, destinationExists, options)) return true; // perform the operation if (performPost(request, response, requestObject, toCreate, options)) { // write the response URI location = URIUtil.append(getURI(request), name); JSONObject result = ServletFileStoreHandler.toJSON(toCreate, toCreate.fetchInfo(), location); OrionServlet.writeJSONResponse(request, response, result); response.setHeader(ProtocolConstants.HEADER_LOCATION, location.toString()); // response code should indicate if a new resource was actually created or not response.setStatus( destinationExists ? HttpServletResponse.SC_OK : HttpServletResponse.SC_CREATED); } return true; }
private static IEditorInput getEditorInput(final IErlElement element0) { IErlElement element = element0; final IResource resource = element.getResource(); if (resource instanceof IFile) { IFile file = (IFile) resource; file = resolveFile(file); return new FileEditorInput(file); } String filePath = element.getFilePath(); while (filePath == null) { final IParent parent = element.getParent(); if (parent instanceof IErlElement) { element = (IErlElement) parent; filePath = element.getFilePath(); } else { break; } } if (filePath != null) { final IPath path = new Path(filePath); IFileStore fileStore = EFS.getLocalFileSystem().getStore(path.removeLastSegments(1)); fileStore = fileStore.getChild(path.lastSegment()); final IFileInfo fetchInfo = fileStore.fetchInfo(); if (!fetchInfo.isDirectory() && fetchInfo.exists()) { if (element instanceof IErlModule && element.getParent() instanceof IErlExternal) { return new ErlangExternalEditorInput(fileStore, (IErlModule) element); } return new FileStoreEditorInput(fileStore); } } return null; }
/** * @param sourceStore the file to be copied * @param sourceRoot the source root * @param destinationRoot the destination root * @param monitor the progress monitor * @return true if the file is successfully copied, false if the operation did not go through for * any reason */ protected boolean copyFile( IFileStore sourceStore, IFileStore sourceRoot, IFileStore destinationRoot, IProgressMonitor monitor) { if (sourceStore == null) { return false; } boolean success = true; IFileStore[] sourceStores = null, targetStores = null; try { if (sourceStore.equals(sourceRoot)) { // copying the whole source sourceStores = sourceRoot.childStores(EFS.NONE, monitor); targetStores = new IFileStore[sourceStores.length]; for (int i = 0; i < targetStores.length; ++i) { targetStores[i] = destinationRoot.getChild(sourceStores[i].getName()); } } else if (sourceRoot.isParentOf(sourceStore)) { // finds the relative path of the file to be copied and maps to // the destination target sourceStores = new IFileStore[1]; sourceStores[0] = sourceStore; targetStores = new IFileStore[1]; String sourceRootPath = sourceRoot.toString(); String sourcePath = sourceStore.toString(); int index = sourcePath.indexOf(sourceRootPath); if (index > -1) { String relativePath = sourcePath.substring(index + sourceRootPath.length()); targetStores[0] = destinationRoot.getFileStore(new Path(relativePath)); // makes sure the parent folder is created on the destination side IFileStore parent = getFolderStore(targetStores[0]); if (parent != targetStores[0]) { parent.mkdir(EFS.NONE, monitor); } } } if (sourceStores == null) { // the file to be copied is not a child of the source root; // cannot copy success = false; sourceStores = new IFileStore[0]; targetStores = new IFileStore[0]; } for (int i = 0; i < sourceStores.length; ++i) { success = copyFile(sourceStores[i], targetStores[i], monitor) && success; } } catch (CoreException e) { // TODO: report the error success = false; } return success; }
/** * Copies an array of sources to the destination location. * * @param sources the array of source file stores * @param destination the file store representing the destination folder * @param monitor an optional progress monitor */ public IStatus copyFiles(IFileStore[] sources, IFileStore destination, IProgressMonitor monitor) { if (monitor == null) { monitor = new NullProgressMonitor(); } int successCount = 0; for (IFileStore source : sources) { if (copyFile(source, destination.getChild(source.getName()), monitor)) { successCount++; } if (fCancelled || monitor.isCanceled()) { return Status.CANCEL_STATUS; } monitor.worked(1); } return new Status(IStatus.OK, IOUIPlugin.PLUGIN_ID, successCount, "OK", null); }
/** * Unzips the transferred file. Returns <code>true</code> if the unzip was successful, and <code> * false</code> otherwise. In case of failure, this method handles setting an appropriate * response. */ private boolean completeUnzip(HttpServletRequest req, HttpServletResponse resp) throws ServletException { IPath destPath = new Path(getPath()); try { ZipFile source = new ZipFile(new File(getStorageDirectory(), FILE_DATA)); IFileStore destinationRoot = NewFileServlet.getFileStore(destPath); Enumeration<? extends ZipEntry> entries = source.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); IFileStore destination = destinationRoot.getChild(entry.getName()); if (entry.isDirectory()) destination.mkdir(EFS.NONE, null); else { destination.getParent().mkdir(EFS.NONE, null); IOUtilities.pipe( source.getInputStream(entry), destination.openOutputStream(EFS.NONE, null), false, true); } } source.close(); } catch (ZipException e) { // zip exception implies client sent us invalid input String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString()); statusHandler.handleRequest( req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, e)); return false; } catch (Exception e) { // other failures should be considered server errors String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString()); statusHandler.handleRequest( req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); return false; } return true; }
/** * Returns the root location where user data files for the given user are stored. In some * configurations this location might be shared across users, so clients will need to ensure * resulting files are segmented appropriately by user. */ public static IFileStore getUserHome(String userId) { URI platformLocationURI = Activator.getDefault().getRootLocationURI(); IFileStore root = null; try { root = EFS.getStore(platformLocationURI); } catch (CoreException e) { // this is fatal, we can't access the platform instance location throw new Error("Failed to access platform instance location", e); // $NON-NLS-1$ } // consult layout preference String layout = PreferenceHelper.getString(ServerConstants.CONFIG_FILE_LAYOUT, "flat") .toLowerCase(); //$NON-NLS-1$ if ("usertree".equals(layout) && userId != null) { // $NON-NLS-1$ // the user-tree layout organises projects by the user who created it String userPrefix = userId.substring(0, Math.min(2, userId.length())); return root.getChild(userPrefix).getChild(userId); } // default layout is a flat list of projects at the root return root; }
public void testLinkedFolderInVirtualFolder_FileStoreURI() { IPath folderLocation = getRandomLocation(); IFolder folder = existingVirtualFolderInExistingProject.getFolder(getUniqueString()); try { folder.createLink(folderLocation, IResource.ALLOW_MISSING_LOCAL, getMonitor()); } catch (CoreException e) { fail("1.0", e); } assertTrue("2.0", folder.exists()); assertEquals("3.0", folderLocation, folder.getLocation()); assertTrue("4.0", !folderLocation.toFile().exists()); // Check file store URI for the linked resource try { IFileStore fs = EFS.getStore(existingVirtualFolderInExistingProject.getLocationURI()); fs = fs.getChild(folder.getName()); assertNotNull("5.0", fs); assertNotNull("6.0", fs.toURI()); } catch (CoreException e) { fail("7.0", e); } }
public IFileStore fileFor(UniversalUniqueIdentifier uuid) { IFileStore root = folderFor(uuid); return root.getChild(bytesToHexString(uuid.toBytes())); }