org.eclipse.core.filesystem.IFileInfo Java Examples

The following examples show how to use org.eclipse.core.filesystem.IFileInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TmfTraceElement.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
private FileInfo computeFileInfo(FileInfo fileInfo, IResource resource) throws CoreException {
    if (fileInfo == null || fileInfo.count > FOLDER_MAX_COUNT) {
        return fileInfo;
    }
    if (resource instanceof IFolder) {
        IFolder folder = (IFolder) resource;
        for (IResource member : folder.members()) {
            computeFileInfo(fileInfo, member);
        }
        return fileInfo;
    }
    IFileInfo info = EFS.getStore(resource.getLocationURI()).fetchInfo();
    fileInfo.lastModified = Math.max(fileInfo.lastModified, info.getLastModified());
    fileInfo.size += info.getLength();
    fileInfo.count++;
    return fileInfo;
}
 
Example #2
Source File: BuildSettingWizardPage.java    From sarl with Apache License 2.0 6 votes vote down vote up
private void rememberExisitingFolders(URI projectLocation) {
	this.orginalFolders = new TreeMap<>();

	try {
		final IFileStore[] children = EFS.getStore(projectLocation).childStores(EFS.NONE, null);
		for (int i = 0; i < children.length; i++) {
			final IFileStore child = children[i];
			final IFileInfo info = child.fetchInfo();
			if (info.isDirectory() && info.exists() && !this.orginalFolders.containsKey(info.getName())) {
				this.orginalFolders.put(info.getName(), child);
			}
		}
	} catch (CoreException e) {
		SARLEclipsePlugin.getDefault().log(e);
	}
}
 
Example #3
Source File: DirectoryHandlerV1.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
public static void encodeChildren(IFileStore dir, URI location, JSONObject result, int depth, boolean addLocation) throws CoreException {
	if (depth <= 0)
		return;
	JSONArray children = new JSONArray();
	//more efficient to ask for child information in bulk for certain file systems
	IFileInfo[] childInfos = dir.childInfos(EFS.NONE, null);
	for (IFileInfo childInfo : childInfos) {
		IFileStore childStore = dir.getChild(childInfo.getName());
		String name = childInfo.getName();
		if (childInfo.isDirectory())
			name += "/"; //$NON-NLS-1$
		URI childLocation = URIUtil.append(location, name);
		JSONObject childResult = ServletFileStoreHandler.toJSON(childStore, childInfo, addLocation ? childLocation : null);
		if (childInfo.isDirectory())
			encodeChildren(childStore, childLocation, childResult, depth - 1);
		children.put(childResult);
	}
	try {
		result.put(ProtocolConstants.KEY_CHILDREN, children);
	} catch (JSONException e) {
		// cannot happen
		throw new RuntimeException(e);
	}
}
 
Example #4
Source File: NewJavaProjectWizardPageTwo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void rememberExisitingFolders(URI projectLocation) {
	fOrginalFolders= new HashSet<IFileStore>();

	try {
		IFileStore[] children= EFS.getStore(projectLocation).childStores(EFS.NONE, null);
		for (int i= 0; i < children.length; i++) {
			IFileStore child= children[i];
			IFileInfo info= child.fetchInfo();
			if (info.isDirectory() && info.exists() && !fOrginalFolders.contains(child.getName())) {
				fOrginalFolders.add(child);
			}
		}
	} catch (CoreException e) {
		JavaPlugin.log(e);
	}
}
 
Example #5
Source File: ManifestUtils.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Inner helper method parsing single manifests with additional semantic analysis.
 */
protected static ManifestParseTree parseManifest(IFileStore manifestFileStore, String targetBase, Analyzer analyzer) throws CoreException, IOException, ParserException, AnalyzerException {

	/* basic sanity checks */
	IFileInfo manifestFileInfo = manifestFileStore.fetchInfo();
	if (!manifestFileInfo.exists() || manifestFileInfo.isDirectory())
		throw new IOException(ManifestConstants.MISSING_OR_INVALID_MANIFEST);

	if (manifestFileInfo.getLength() == EFS.NONE)
		throw new IOException(ManifestConstants.EMPTY_MANIFEST);

	if (manifestFileInfo.getLength() > ManifestConstants.MANIFEST_SIZE_LIMIT)
		throw new IOException(ManifestConstants.MANIFEST_FILE_SIZE_EXCEEDED);

	InputStream inputStream = manifestFileStore.openInputStream(EFS.NONE, null);
	ManifestParseTree manifestTree = null;
	try {
		manifestTree = parseManifest(inputStream, targetBase, analyzer);
	} finally {
		if (inputStream != null) {
			inputStream.close();
		}
	}
	return manifestTree;
}
 
Example #6
Source File: CreateFileChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
	RefactoringStatus result= new RefactoringStatus();
	IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);

	URI location= file.getLocationURI();
	if (location == null) {
		result.addFatalError(Messages.format(
			NLSChangesMessages.CreateFileChange_error_unknownLocation,
			BasicElementLabels.getPathLabel(file.getFullPath(), false)));
		return result;
	}

	IFileInfo jFile= EFS.getStore(location).fetchInfo();
	if (jFile.exists()) {
		result.addFatalError(Messages.format(
			NLSChangesMessages.CreateFileChange_error_exists,
			BasicElementLabels.getPathLabel(file.getFullPath(), false)));
		return result;
	}
	return result;
}
 
Example #7
Source File: RefreshHandler.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
void checkLocationDeleted(final IProject project) throws CoreException {
	if (!project.exists()) { return; }
	final IFileInfo location = IDEResourceInfoUtils.getFileInfo(project.getLocationURI());
	if (!location.exists()) {
		final String message = NLS.bind(IDEWorkbenchMessages.RefreshAction_locationDeletedMessage,
				project.getName(), location.toString());

		final MessageDialog dialog = new MessageDialog(WorkbenchHelper.getShell(),
				IDEWorkbenchMessages.RefreshAction_dialogTitle, null, message, MessageDialog.QUESTION,
				new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 0) {
			@Override
			protected int getShellStyle() {
				return super.getShellStyle() | SWT.SHEET;
			}
		};
		WorkbenchHelper.run(() -> dialog.open());

		// Do the deletion back in the operation thread
		if (dialog.getReturnCode() == 0) { // yes was chosen
			project.delete(true, true, null);
		}
	}
}
 
Example #8
Source File: FileOpener.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public static IEditorPart openFileInFileSystem(final URI uri) throws PartInitException {
	if (uri == null) { return null; }
	IFileStore fileStore;
	try {
		fileStore = EFS.getLocalFileSystem().getStore(Path.fromOSString(uri.toFileString()));
	} catch (final Exception e1) {
		MessageDialog.openWarning(WorkbenchHelper.getShell(), "No file found",
				"The file'" + uri.toString() + "' cannot be found.");
		return null;
	}
	IFileInfo info;
	try {
		info = fileStore.fetchInfo();
	} catch (final Exception e) {
		MessageDialog.openWarning(WorkbenchHelper.getShell(), "No file found",
				"The file'" + uri.toString() + "' cannot be found.");
		return null;
	}
	if (!info.exists()) {
		MessageDialog.openWarning(WorkbenchHelper.getShell(), "No file found",
				"The file'" + uri.toString() + "' cannot be found.");
	}
	return IDE.openInternalEditorOnFileStore(PAGE, fileStore);
}
 
Example #9
Source File: CreateFileChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
	RefactoringStatus result= new RefactoringStatus();
	IFile file= ResourcesPlugin.getWorkspace().getRoot().getFile(fPath);

	URI location= file.getLocationURI();
	if (location == null) {
		result.addFatalError(Messages.format(
			NLSChangesMessages.CreateFileChange_error_unknownLocation,
			BasicElementLabels.getPathLabel(file.getFullPath(), false)));
		return result;
	}

	IFileInfo jFile= EFS.getStore(location).fetchInfo();
	if (jFile.exists()) {
		result.addFatalError(Messages.format(
			NLSChangesMessages.CreateFileChange_error_exists,
			BasicElementLabels.getPathLabel(file.getFullPath(), false)));
		return result;
	}
	return result;
}
 
Example #10
Source File: RefreshAction.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Checks whether the given project's location has been deleted. If so, prompts the user with whether to delete the
 * project or not.
 */
void checkLocationDeleted(final IProject project) throws CoreException {
	if (!project.exists()) { return; }
	final IFileInfo location = IDEResourceInfoUtils.getFileInfo(project.getLocationURI());
	if (!location.exists()) {
		final String message = NLS.bind(IDEWorkbenchMessages.RefreshAction_locationDeletedMessage,
				project.getName(), location.toString());

		final MessageDialog dialog =
				new MessageDialog(WorkbenchHelper.getShell(), IDEWorkbenchMessages.RefreshAction_dialogTitle, null,
						message, QUESTION, new String[] { YES_LABEL, NO_LABEL }, 0) {
					@Override
					protected int getShellStyle() {
						return super.getShellStyle() | SHEET;
					}
				};
		WorkbenchHelper.run(() -> dialog.open());

		// Do the deletion back in the operation thread
		if (dialog.getReturnCode() == 0) { // yes was chosen
			project.delete(true, true, null);
		}
	}
}
 
Example #11
Source File: SftpFileStore.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void delete(int options, IProgressMonitor monitor) throws CoreException {
	SynchronizedChannel channel = getChannel();
	try {
		//we need to know if we are a directory or file, but used the last fetched info if available
		IFileInfo info = cachedInfo;
		//use local field in case of concurrent change to cached info
		if (info == null)
			info = fetchInfo();
		if (info.isDirectory())
			channel.rmdir(getPathString(channel));
		else
			channel.rm(getPathString(channel));
	} catch (Exception e) {
		ChannelCache.flush(host);
		throw wrap(e);
	}
}
 
Example #12
Source File: Storage2UriMapperImpl.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private Iterable<Pair<IStorage, IProject>> getStorages(/* @NonNull */ URI uri, IFile file) {
	if (file == null || !file.isAccessible()) {
		Iterable<Pair<IStorage, IProject>> result = contribution.getStorages(uri);
		if (result == null || !result.iterator().hasNext()) {
			 // Handle files external to the workspace. But check contribution first to be backwards compatible.
			if (uri.isFile()) {
				Path filePath = new Path(uri.toFileString());
				IFileStore fileStore = EFS.getLocalFileSystem().getStore(filePath);
				IFileInfo fileInfo = fileStore.fetchInfo();
				if (fileInfo.exists() && !fileInfo.isDirectory()) {
					return Collections.singletonList(
							Tuples.<IStorage, IProject> create(new FileStoreStorage(fileStore, fileInfo, filePath), (IProject) null));
				}
			}
		}
		return result;
	}
	return Collections.singleton(Tuples.<IStorage, IProject> create(file, file.getProject()));
}
 
Example #13
Source File: FileTree.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public IFileInfo getFileInfo(IFileStore store) {
	IFileInfo result = infoMap.get(store);
	if (result != null) {
		return result;
	}
	return new FileInfo(store.getName());
}
 
Example #14
Source File: NestedProjectFilter.java    From eclipse-extras with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean matches( IContainer parent, IFileInfo fileInfo ) {
  if( !fileInfo.isDirectory() || recursionGuard.isInUse( project )) {
    return false;
  }
  recursionGuard.enter( project );
  try {
    return findContainer( parent, fileInfo.getName() )
      .stream()
      .anyMatch( container -> container.getType() == PROJECT && !container.equals( project ) );
  } finally {
    recursionGuard.leave( project );
  }
}
 
Example #15
Source File: FileUtils.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
private static String findOutsideWorkspace(final String fp, final URI modelBase, final boolean mustExist) {
	if (!mustExist) { return fp; }
	final IFileStore file = FILE_SYSTEM.getStore(new Path(fp));
	final IFileInfo info = file.fetchInfo();
	if (info.exists()) {
		final IFile linkedFile = createLinkToExternalFile(fp, modelBase);
		if (linkedFile == null) { return fp; }
		return linkedFile.getLocation().toFile().getAbsolutePath();
	}
	return null;
}
 
Example #16
Source File: ResourceManager.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public boolean validateLocation(final IFile resource) {
	if (!resource.isLinked()) { return true; }
	if (DEBUG.IS_ON()) {
		DEBUG.OUT("Validating link location of " + resource);
	}
	final boolean internal =
			ResourcesPlugin.getWorkspace().validateLinkLocation(resource, resource.getLocation()).isOK();
	if (!internal) { return false; }
	final IFileStore file = EFS.getLocalFileSystem().getStore(resource.getLocation());
	final IFileInfo info = file.fetchInfo();
	return info.exists();
}
 
Example #17
Source File: FileTree.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public IFileInfo[] getChildInfos(IFileStore store) {
	IFileStore[] result = treeMap.get(store);
	if (result != null) {
		List<IFileInfo> list = new ArrayList<IFileInfo>();
		for (IFileStore file : result) {
			list.add(infoMap.get(file));
		}
		return list.toArray(new IFileInfo[list.size()]);
	}
	return EMPTY_FILE_INFO_ARRAY;
}
 
Example #18
Source File: FileUtils.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a best guess URI based on the target string and an optional URI specifying from where the relative URI
 * should be run. If existingResource is null, then the root of the workspace is used as the relative URI
 *
 * @param target
 *            a String giving the path
 * @param existingResource
 *            the URI of the resource from which relative URIs should be interpreted
 * @author Alexis Drogoul, July 2018
 * @return an URI or null if it cannot be determined.
 */
public static URI getURI(final String target, final URI existingResource) {
	if (target == null) { return null; }
	try {
		final IPath path = Path.fromOSString(target);
		final IFileStore file = EFS.getLocalFileSystem().getStore(path);
		final IFileInfo info = file.fetchInfo();
		if (info.exists()) {
			// We have an absolute file
			final URI fileURI = URI.createFileURI(target);
			return fileURI;
		} else {
			final URI first = URI.createURI(target, false);
			URI root;
			if (!existingResource.isPlatformResource()) {
				root = URI.createPlatformResourceURI(existingResource.toString(), false);
			} else {
				root = existingResource;
			}
			if (root == null) {
				root = WORKSPACE_URI;
			}
			final URI iu = first.resolve(root);
			if (isFileExistingInWorkspace(iu)) { return iu; }
			return null;
		}
	} catch (final Exception e) {
		return null;
	}
}
 
Example #19
Source File: WorkspaceFile.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public IFileInfo fetchInfo(int options, IProgressMonitor monitor) throws CoreException {
	ensureLocalFileStore();
	if (localFileStore != null) {
		FileInfo fileInfo = (FileInfo) localFileStore.fetchInfo(options, monitor);
		if (path.isRoot()) {
			fileInfo.setName(path.toPortableString());
		}
		return fileInfo;
	}
	FileInfo info = new FileInfo(path.lastSegment());
	info.setExists(false);
	return info;
}
 
Example #20
Source File: WorkspaceFile.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void putInfo(IFileInfo info, int options, IProgressMonitor monitor) throws CoreException {
	ensureLocalFileStore();
	if (localFileStore != null) {
		localFileStore.putInfo(info, options, monitor);
	} else {
		Policy.error(EFS.ERROR_NOT_EXISTS, NLS.bind(Messages.fileNotFound, path));
	}
}
 
Example #21
Source File: LocalWebServerHttpRequestHandler.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
private static IFileInfo getIndex(IFileStore parent) throws CoreException
{
	for (IFileInfo fileInfo : parent.childInfos(EFS.NONE, new NullProgressMonitor()))
	{
		if (fileInfo.exists() && PATTERN_INDEX.matcher(fileInfo.getName()).matches())
		{
			return fileInfo;
		}
	}
	return EFS.getNullFileSystem().getStore(Path.EMPTY).fetchInfo();
}
 
Example #22
Source File: JarWriter3.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the directory entries for the given path and writes it to the
 * current archive.
 *
 * @param resource
 *            the resource for which the parent directories are to be added
 * @param destinationPath
 *            the path to add
 *
 * @throws IOException
 *             if an I/O error has occurred
 * @throws CoreException
 *             if accessing the resource failes
 */
protected void addDirectories(IResource resource, IPath destinationPath) throws IOException, CoreException {
	IContainer parent= null;
	String path= destinationPath.toString().replace(File.separatorChar, '/');
	int lastSlash= path.lastIndexOf('/');
	List<JarEntry> directories= new ArrayList<JarEntry>(2);
	while (lastSlash != -1) {
		path= path.substring(0, lastSlash + 1);
		if (!fDirectories.add(path))
			break;

		parent= resource.getParent();
		long timeStamp= System.currentTimeMillis();
		URI location= parent.getLocationURI();
		if (location != null) {
			IFileInfo info= EFS.getStore(location).fetchInfo();
			if (info.exists())
				timeStamp= info.getLastModified();
		}

		JarEntry newEntry= new JarEntry(path);
		newEntry.setMethod(ZipEntry.STORED);
		newEntry.setSize(0);
		newEntry.setCrc(0);
		newEntry.setTime(timeStamp);
		directories.add(newEntry);

		lastSlash= path.lastIndexOf('/', lastSlash - 1);
	}

	for (int i= directories.size() - 1; i >= 0; --i) {
		fJarOutputStream.putNextEntry(directories.get(i));
	}
}
 
Example #23
Source File: JarWriter3.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new JarEntry with the passed path and contents, and writes it
 * to the current archive.
 *
 * @param	resource			the file to write
 * @param	path				the path inside the archive
 *
    * @throws	IOException			if an I/O error has occurred
 * @throws	CoreException 		if the resource can-t be accessed
 */
protected void addFile(IFile resource, IPath path) throws IOException, CoreException {
	JarEntry newEntry= new JarEntry(path.toString().replace(File.separatorChar, '/'));
	byte[] readBuffer= new byte[4096];

	if (fJarPackage.isCompressed())
		newEntry.setMethod(ZipEntry.DEFLATED);
		// Entry is filled automatically.
	else {
		newEntry.setMethod(ZipEntry.STORED);
		JarPackagerUtil.calculateCrcAndSize(newEntry, resource.getContents(false), readBuffer);
	}

	long lastModified= System.currentTimeMillis();
	URI locationURI= resource.getLocationURI();
	if (locationURI != null) {
		IFileInfo info= EFS.getStore(locationURI).fetchInfo();
		if (info.exists())
			lastModified= info.getLastModified();
	}

	// Set modification time
	newEntry.setTime(lastModified);

	InputStream contentStream = resource.getContents(false);

	addEntry(newEntry, contentStream);
}
 
Example #24
Source File: IDEEditputProvider.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
public IEditorInput createEditorInput( Object file )
{
	if (file instanceof File)
	{
		File handle = (File)file;
		String fileName = handle.getAbsolutePath( );
		
		IWorkspace space = ResourcesPlugin.getWorkspace( );
		IWorkspaceRoot root = space.getRoot( );
		try
		{
			//IFile[] resources = root.findFilesForLocationURI( new URL("file:///" + fileName ).toURI( ) ); //$NON-NLS-1$
			IFile[] resources = root.findFilesForLocationURI(new File( fileName ).toURI( ) ); //$NON-NLS-1$
			if (resources != null && resources.length > 0)
			{
				IEditorInput input = new FileEditorInput(resources[0]);
				return input;
			}
			else
			{
				IFileStore fileStore =  EFS.getLocalFileSystem().getStore(new Path(fileName));
				IFileInfo fetchInfo = fileStore.fetchInfo();
				if (!fetchInfo.isDirectory() && fetchInfo.exists())
				{
					return new FileStoreEditorInput(fileStore);
				}
			}
		}
		catch(Exception e)
		{
			return null;
		}
	}
	return null;
}
 
Example #25
Source File: CopyFilesAndFoldersOperation.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether the resources with the given names exist.
 *
 * @param resources
 *            IResources to checl
 * @return Multi status with one error message for each missing file.
 */
IStatus checkExist(IResource[] resources) {
    MultiStatus multiStatus = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, getProblemsMessage(), null);

    for (int i = 0; i < resources.length; i++) {
        IResource resource = resources[i];
        if (resource != null) {
            URI location = resource.getLocationURI();
            String message = null;
            if (location != null) {
                IFileInfo info = IDEResourceInfoUtils.getFileInfo(location);
                if (info == null || info.exists() == false) {
                    if (resource.isLinked()) {
                        message = NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_missingLinkTarget,
                                resource.getName());
                    } else {
                        message = NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_resourceDeleted,
                                resource.getName());
                    }
                }
            }
            if (message != null) {
                IStatus status = new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.OK, message, null);
                multiStatus.add(status);
            }
        }
    }
    return multiStatus;
}
 
Example #26
Source File: RemoteImportTracesOperation.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private IResource downloadFileTrace(IFileStore trace, IFolder traceFolder, IProgressMonitor monitor) throws CoreException, IOException, InterruptedException {

        IFolder folder = traceFolder;
        String traceName = trace.getName();

        traceName = TmfTraceCoreUtils.validateName(traceName);

        IResource resource = folder.findMember(traceName);
        if ((resource != null) && resource.exists()) {
            String newName = fConflictHandler.checkAndHandleNameClash(resource.getFullPath(), monitor);
            if (newName == null) {
                return null;
            }
            traceName = newName;
        }
        SubMonitor subMonitor = SubMonitor.convert(monitor, 1);
        subMonitor.beginTask(RemoteMessages.RemoteImportTracesOperation_DownloadTask, 1);

        IPath destination = folder.getLocation().addTrailingSeparator().append(traceName);
        IFileInfo info = trace.fetchInfo();
        subMonitor.setTaskName(RemoteMessages.RemoteImportTracesOperation_DownloadTask + ' ' + trace.getName() + '/' + trace.getName());
        try (InputStream in = trace.openInputStream(EFS.NONE, new NullProgressMonitor())) {
            copy(in, folder, destination, subMonitor, info.getLength());
        }
        folder.refreshLocal(IResource.DEPTH_INFINITE, null);
        return folder.findMember(traceName);
    }
 
Example #27
Source File: Packager.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
protected void writeZip(IFileStore source, IPath path, ZipOutputStream zos) throws CoreException, IOException {

		/* load .cfignore if present */
		IFileStore cfIgnoreFile = source.getChild(CF_IGNORE_FILE);
		if (cfIgnoreFile.fetchInfo().exists()) {

			IgnoreNode node = new IgnoreNode();
			InputStream is = null;

			try {

				is = cfIgnoreFile.openInputStream(EFS.NONE, null);
				node.parse(is);

				cfIgnore.put(source.toURI(), node);

			} finally {
				if (is != null)
					is.close();
			}
		}

		IFileInfo info = source.fetchInfo(EFS.NONE, null);

		if (info.isDirectory()) {

			if (!isIgnored(source, path, true))
				for (IFileStore child : source.childStores(EFS.NONE, null))
					writeZip(child, path.append(child.getName()), zos);

		} else {

			if (!isIgnored(source, path, false)) {
				ZipEntry entry = new ZipEntry(path.toString());
				zos.putNextEntry(entry);
				IOUtilities.pipe(source.openInputStream(EFS.NONE, null), zos, true, false);
			}
		}
	}
 
Example #28
Source File: SearchResult.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Provides a JSON representation of the search result.
 * @param contextPath the context path of the server that is added to the location for the result.
 * @return a JSON representation of the search result.
 * @throws URISyntaxException
 * @throws JSONException
 * @throws CoreException
 */
public JSONObject toJSON(String contextPath) throws URISyntaxException, JSONException, CoreException {
	JSONObject doc = new JSONObject();

	IFileInfo fileInfo = getFileStore().fetchInfo();
	// Set file details
	doc.put(ProtocolConstants.KEY_NAME, fileInfo.getName());
	doc.put(ProtocolConstants.KEY_LENGTH, fileInfo.getLength());
	doc.put(ProtocolConstants.KEY_DIRECTORY, fileInfo.isDirectory());
	doc.put(ProtocolConstants.KEY_LAST_MODIFIED, fileInfo.getLastModified());
	// Prepare project data
	IFileStore projectStore = getProject().getProjectStore();
	int projectLocationLength = projectStore.toURI().toString().length();
	IPath projectLocation;
	if (contextPath.length() != 0) {
		projectLocation = new Path(contextPath).append(Activator.LOCATION_FILE_SERVLET).append(getWorkspace().getUniqueId()).append(getProject().getFullName()).addTrailingSeparator();
	} else {
		projectLocation = new Path(Activator.LOCATION_FILE_SERVLET).append(getWorkspace().getUniqueId()).append(getProject().getFullName()).addTrailingSeparator();
	}
	String projectRelativePath = getFileStore().toURI().toString().substring(projectLocationLength);
	// Add location to json
	IPath fileLocation = projectLocation.append(projectRelativePath);
	doc.put(ProtocolConstants.KEY_LOCATION, fileLocation.toString());
	String projectName = getProject().getFullName();
	//Projects with no name are due to an old bug where project metadata was not deleted  see bug 367333.
	if (projectName != null)
		doc.put(ProtocolConstants.KEY_PATH, new Path(projectName).append(projectRelativePath));
	return doc;
}
 
Example #29
Source File: NewFileServlet.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	traceRequest(req);
	String pathInfo = req.getPathInfo();
	IPath path = pathInfo == null ? Path.ROOT : new Path(pathInfo);

	// prevent path canonicalization hacks
	if (pathInfo != null && !pathInfo.equals(path.toString())) {
		handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, NLS.bind("Forbidden: {0}", pathInfo), null));
		return;
	}
	//don't allow anyone to mess with metadata
	if (path.segmentCount() > 0 && ".metadata".equals(path.segment(0))) { //$NON-NLS-1$
		handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, NLS.bind("Forbidden: {0}", pathInfo), null));
		return;
	}
	IFileStore file = getFileStore(req, path);
	IFileStore testLink = file;
	while (testLink != null) {
		IFileInfo info = testLink.fetchInfo();
		if (info.getAttribute(EFS.ATTRIBUTE_SYMLINK)) {
			if (file == testLink) {
				handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_FORBIDDEN, NLS.bind("Forbidden: {0}", EncodingUtils.encodeForHTML(pathInfo.toString())), null));
			} else {
				handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, NLS.bind("File not found: {0}", EncodingUtils.encodeForHTML(pathInfo.toString())), null));
			}
			return;
		}
		testLink = testLink.getParent();
	}

	if (file == null) {
		handleException(resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, NLS.bind("File not found: {0}", EncodingUtils.encodeForHTML(pathInfo.toString())), null));
		return;
	}
	if (fileSerializer.handleRequest(req, resp, file))
		return;
	// finally invoke super to return an error for requests we don't know how to handle
	super.doGet(req, resp);
}
 
Example #30
Source File: SftpFileStore.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public IFileInfo fetchInfo(int options, IProgressMonitor monitor) throws CoreException {
	SynchronizedChannel channel = getChannel();
	try {
		SftpATTRS stat = channel.stat(getPathString(channel));
		cachedInfo = attrsToInfo(getName(), stat);
		return cachedInfo;
	} catch (Exception e) {
		ChannelCache.flush(host);
		throw wrap(e);
	}
}