Java Code Examples for org.eclipse.core.resources.IResourceStatus

The following are top voted examples for showing how to use org.eclipse.core.resources.IResourceStatus. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: egradle   File: PathException.java   Source Code and License 6 votes vote down vote up
public void printStackTrace(T output) {
	synchronized (output) {
		IStatus status = getStatus();
		Throwable exception = status.getException();
		if (exception != null) {
			String path = "()"; //$NON-NLS-1$
			if (status instanceof IResourceStatus) {
				path = "(" + ((IResourceStatus) status).getPath() + ")"; //$NON-NLS-1$ //$NON-NLS-2$
			}
			String s = getClass().getName() + path + "[" + status.getCode() + "]: ";
			print(output, s); // $NON-NLS-1$ //$NON-NLS-2$
			exceptionPrintStackTrace(exception, output);
		} else
			superPrintStackTrace(output);
	}
}
 
Example 2
Project: subclipse   File: SynchronizerSyncInfoCache.java   Source Code and License 6 votes vote down vote up
public void purgeCache(IContainer root, boolean deep) throws SVNException {
	int depth = deep ? IResource.DEPTH_INFINITE : IResource.DEPTH_ZERO;
	try {
		if (root.exists() || root.isPhantom()) {
			ResourcesPlugin.getWorkspace().getSynchronizer().flushSyncInfo(StatusCacheManager.SVN_BC_SYNC_KEY, root, depth);
		}
		if (deep) {
			accessor.removeRecursiveFromPendingCache(root);
		} else {
			accessor.removeFromPendingCache(root);
		}
	} catch (CoreException e) {
		if (e.getStatus().getCode() == IResourceStatus.RESOURCE_NOT_FOUND) {
			// Must have been deleted since we checked
			return;
		}
		throw SVNException.wrapException(e);
	}		
}
 
Example 3
Project: subclipse   File: SVNWorkspaceSubscriber.java   Source Code and License 6 votes vote down vote up
public boolean isSupervised(IResource resource) throws TeamException {
try {
	if (resource.isTeamPrivateMember() || SVNWorkspaceRoot.isLinkedResource(resource)) return false;
	RepositoryProvider provider = RepositoryProvider.getProvider(resource.getProject(), SVNProviderPlugin.getTypeId());
	if (provider == null) return false;
	// TODO: what happens for resources that don't exist?
	// TODO: is it proper to use ignored here?
	ISVNLocalResource svnThing = SVNWorkspaceRoot.getSVNResourceFor(resource);
	if (svnThing.isIgnored()) {
		// An ignored resource could have an incoming addition (conflict)
		return (remoteSyncStateStore.getBytes(resource) != null) || 
				((remoteSyncStateStore.members(resource) != null) && (remoteSyncStateStore.members(resource).length > 0));
	}
	return true;
} catch (TeamException e) {
	// If there is no resource in coe this measn there is no local and no remote
	// so the resource is not supervised.
	if (e.getStatus().getCode() == IResourceStatus.RESOURCE_NOT_FOUND) {
		return false;
	}
	throw e;
}
  }
 
Example 4
Project: cmake4eclipse   File: BuildscriptGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * Recursively creates the folder hierarchy needed for the build output, if
 * necessary. If the folder is created, its derived bit is set to true so the
 * CM system ignores the contents. If the resource exists, respect the
 * existing derived setting.
 *
 * @param folder
 *        a folder, somewhere below the project root
 */
private void createFolder(IFolder folder) throws CoreException {
  if (!folder.exists()) {
    // Make sure that parent folders exist
    IContainer parent = folder.getParent();
    if (parent instanceof IFolder && !parent.exists()) {
      createFolder((IFolder) parent);
    }

    // Now make the requested folder
    try {
      folder.create(IResource.DERIVED, true, monitor);
    } catch (CoreException e) {
      if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
        folder.refreshLocal(IResource.DEPTH_ZERO, monitor);
      else
        throw e;
    }
  }
}
 
Example 5
Project: che   File: WorkManager.java   Source Code and License 6 votes vote down vote up
/** An operation calls this method and it only returns when the operation is free to run. */
public void checkIn(ISchedulingRule rule, IProgressMonitor monitor) throws CoreException {
  boolean success = false;
  try {
    if (workspace.isTreeLocked()) {
      String msg = Messages.resources_cannotModify;
      throw new ResourceException(IResourceStatus.WORKSPACE_LOCKED, null, msg, null);
    }
    jobManager.beginRule(rule, monitor);
    lock.acquire();
    incrementPreparedOperations();
    success = true;
  } finally {
    // remember if we failed to check in, so we can avoid check out
    if (!success) checkInFailed.set(Boolean.TRUE);
  }
}
 
Example 6
Project: che   File: ResourceException.java   Source Code and License 6 votes vote down vote up
/**
 * Prints a stack trace out for the exception, and any nested exception that it may have embedded
 * in its Status object.
 */
@Override
public void printStackTrace(PrintStream output) {
  synchronized (output) {
    IStatus status = getStatus();
    if (status.getException() != null) {
      String path = "()"; // $NON-NLS-1$
      if (status instanceof IResourceStatus)
        path = "(" + ((IResourceStatus) status).getPath() + ")"; // $NON-NLS-1$ //$NON-NLS-2$
      output.print(
          getClass().getName()
              + path
              + "["
              + status.getCode()
              + "]: "); // $NON-NLS-1$ //$NON-NLS-2$
      status.getException().printStackTrace(output);
    } else super.printStackTrace(output);
  }
}
 
Example 7
Project: che   File: ResourceException.java   Source Code and License 6 votes vote down vote up
/**
 * Prints a stack trace out for the exception, and any nested exception that it may have embedded
 * in its Status object.
 */
@Override
public void printStackTrace(PrintWriter output) {
  synchronized (output) {
    IStatus status = getStatus();
    if (status.getException() != null) {
      String path = "()"; // $NON-NLS-1$
      if (status instanceof IResourceStatus)
        path = "(" + ((IResourceStatus) status).getPath() + ")"; // $NON-NLS-1$ //$NON-NLS-2$
      output.print(
          getClass().getName()
              + path
              + "["
              + status.getCode()
              + "]: "); // $NON-NLS-1$ //$NON-NLS-2$
      status.getException().printStackTrace(output);
    } else super.printStackTrace(output);
  }
}
 
Example 8
Project: APICloud-Studio   File: SynchronizerSyncInfoCache.java   Source Code and License 6 votes vote down vote up
public void purgeCache(IContainer root, boolean deep) throws SVNException {
	int depth = deep ? IResource.DEPTH_INFINITE : IResource.DEPTH_ZERO;
	try {
		if (root.exists() || root.isPhantom()) {
			ResourcesPlugin.getWorkspace().getSynchronizer().flushSyncInfo(StatusCacheManager.SVN_BC_SYNC_KEY, root, depth);
		}
		if (deep) {
			accessor.removeRecursiveFromPendingCache(root);
		} else {
			accessor.removeFromPendingCache(root);
		}
	} catch (CoreException e) {
		if (e.getStatus().getCode() == IResourceStatus.RESOURCE_NOT_FOUND) {
			// Must have been deleted since we checked
			return;
		}
		throw SVNException.wrapException(e);
	}		
}
 
Example 9
Project: APICloud-Studio   File: SVNWorkspaceSubscriber.java   Source Code and License 6 votes vote down vote up
public boolean isSupervised(IResource resource) throws TeamException {
try {
	if (resource.isTeamPrivateMember() || SVNWorkspaceRoot.isLinkedResource(resource)) return false;
	RepositoryProvider provider = RepositoryProvider.getProvider(resource.getProject(), SVNProviderPlugin.getTypeId());
	if (provider == null) return false;
	// TODO: what happens for resources that don't exist?
	// TODO: is it proper to use ignored here?
	ISVNLocalResource svnThing = SVNWorkspaceRoot.getSVNResourceFor(resource);
	if (svnThing.isIgnored()) {
		// An ignored resource could have an incoming addition (conflict)
		return (remoteSyncStateStore.getBytes(resource) != null) || 
				((remoteSyncStateStore.members(resource) != null) && (remoteSyncStateStore.members(resource).length > 0));
	}
	return true;
} catch (TeamException e) {
	// If there is no resource in coe this measn there is no local and no remote
	// so the resource is not supervised.
	if (e.getStatus().getCode() == IResourceStatus.RESOURCE_NOT_FOUND) {
		return false;
	}
	throw e;
}
  }
 
Example 10
Project: APICloud-Studio   File: ProblemsLabelDecorator.java   Source Code and License 6 votes vote down vote up
/**
 * Compute the flags that were set on the give object. We expect an IResource for this computation, and we return
 * the flags according to the warnings or errors set on the resource.
 * 
 * @param obj
 *            A IResource (expected)
 * @return An integer representing an ERROR or a WARNING; -1 if the give object was not an IResource or when we got
 *         an exception retrieving the {@link IMarker}s from the resource.
 */
protected int computeAdornmentFlags(Object obj)
{
	try
	{
		if (obj instanceof IResource)
		{
			return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE);
		}
	}
	catch (CoreException e)
	{
		if (e.getStatus().getCode() == IResourceStatus.MARKER_NOT_FOUND)
		{
			return -1;
		}
		IdeLog.logWarning(EditorEplPlugin.getDefault(),
				"Error computing label-decoration adornment flags", e, EditorEplPlugin.DEBUG_SCOPE); //$NON-NLS-1$
	}
	return -1;
}
 
Example 11
Project: Eclipse-Postfix-Code-Completion   File: Resources.java   Source Code and License 6 votes vote down vote up
private static IStatus addOutOfSync(IStatus status, IResource resource) {
	IStatus entry= new Status(
		IStatus.ERROR,
		ResourcesPlugin.PI_RESOURCES,
		IResourceStatus.OUT_OF_SYNC_LOCAL,
		Messages.format(CorextMessages.Resources_outOfSync, BasicElementLabels.getPathLabel(resource.getFullPath(), false)),
		null);
	if (status == null) {
		return entry;
	} else if (status.isMultiStatus()) {
		((MultiStatus)status).add(entry);
		return status;
	} else {
		MultiStatus result= new MultiStatus(
			ResourcesPlugin.PI_RESOURCES,
			IResourceStatus.OUT_OF_SYNC_LOCAL,
			CorextMessages.Resources_outOfSyncResources, null);
		result.add(status);
		result.add(entry);
		return result;
	}
}
 
Example 12
Project: Eclipse-Postfix-Code-Completion   File: BatchOperation.java   Source Code and License 6 votes vote down vote up
protected void executeOperation() throws JavaModelException {
	try {
		this.runnable.run(this.progressMonitor);
	} catch (CoreException ce) {
		if (ce instanceof JavaModelException) {
			throw (JavaModelException)ce;
		} else {
			if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
				Throwable e= ce.getStatus().getException();
				if (e instanceof JavaModelException) {
					throw (JavaModelException) e;
				}
			}
			throw new JavaModelException(ce);
		}
	}
}
 
Example 13
Project: Eclipse-Postfix-Code-Completion-Juno38   File: Resources.java   Source Code and License 6 votes vote down vote up
private static IStatus addOutOfSync(IStatus status, IResource resource) {
	IStatus entry= new Status(
		IStatus.ERROR,
		ResourcesPlugin.PI_RESOURCES,
		IResourceStatus.OUT_OF_SYNC_LOCAL,
		Messages.format(CorextMessages.Resources_outOfSync, BasicElementLabels.getPathLabel(resource.getFullPath(), false)),
		null);
	if (status == null) {
		return entry;
	} else if (status.isMultiStatus()) {
		((MultiStatus)status).add(entry);
		return status;
	} else {
		MultiStatus result= new MultiStatus(
			ResourcesPlugin.PI_RESOURCES,
			IResourceStatus.OUT_OF_SYNC_LOCAL,
			CorextMessages.Resources_outOfSyncResources, null);
		result.add(status);
		result.add(entry);
		return result;
	}
}
 
Example 14
Project: Eclipse-Postfix-Code-Completion-Juno38   File: BatchOperation.java   Source Code and License 6 votes vote down vote up
protected void executeOperation() throws JavaModelException {
	try {
		this.runnable.run(this.progressMonitor);
	} catch (CoreException ce) {
		if (ce instanceof JavaModelException) {
			throw (JavaModelException)ce;
		} else {
			if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
				Throwable e= ce.getStatus().getException();
				if (e instanceof JavaModelException) {
					throw (JavaModelException) e;
				}
			}
			throw new JavaModelException(ce);
		}
	}
}
 
Example 15
Project: subclipse   File: TeamAction.java   Source Code and License 5 votes vote down vote up
/**
 * Method invoked from <code>selectionChanged(IAction, ISelection)</code> 
 * to set the enablement status of the action. The instance variable 
 * <code>selection</code> will contain the latest selection so the methods
 * <code>getSelectedResources()</code> and <code>getSelectedProjects()</code>
 * will provide the proper objects.
 * 
 * This method can be overridden by subclasses but should not be invoked by them.
 */
protected void setActionEnablement(IAction action) {
	try {
		action.setEnabled(isEnabled());
	} catch (TeamException e) {
		if (e.getStatus().getCode() == IResourceStatus.OUT_OF_SYNC_LOCAL) {
			// Enable the action to allow the user to discover the problem
			action.setEnabled(true);
		} else {
			action.setEnabled(false);
			// We should not open a dialog when determining menu enablements so log it instead
			SVNUIPlugin.log(e);
		}
	}
}
 
Example 16
Project: subclipse   File: RemoteAnnotationStorage.java   Source Code and License 5 votes vote down vote up
public String getCharset() throws CoreException {
	InputStream contents = getContents();
	try {
		String charSet = SVNUIPlugin.getCharset(getName(), contents);
		return charSet;
	} catch (IOException e) {
		throw new SVNException(new Status(IStatus.ERROR, SVNUIPlugin.ID, IResourceStatus.FAILED_DESCRIBING_CONTENTS, Policy.bind("RemoteAnnotationStorage.1", getFullPath().toString()), e)); //$NON-NLS-1$
	} finally {
		try {
			contents.close();
		} catch (IOException e1) {
			// Ignore
		}
	}
}
 
Example 17
Project: che   File: Workspace.java   Source Code and License 5 votes vote down vote up
/**
 * We should not have direct references to this field. All references should go through this
 * method.
 */
public WorkManager getWorkManager() throws CoreException {
  if (_workManager == null) {
    String message = Messages.resources_shutdown;
    throw new ResourceException(
        new ResourceStatus(IResourceStatus.INTERNAL_ERROR, null, message));
  }
  return _workManager;
}
 
Example 18
Project: che   File: Workspace.java   Source Code and License 5 votes vote down vote up
@Override
public IStatus validateName(String segment, int type) {
  String message;
  /* segment must not be null */
  if (segment == null) {
    message = Messages.resources_nameNull;
    return new org.eclipse.core.internal.resources.ResourceStatus(
        IResourceStatus.INVALID_VALUE, null, message);
  }

  // cannot be an empty string
  if (segment.length() == 0) {
    message = Messages.resources_nameEmpty;
    return new org.eclipse.core.internal.resources.ResourceStatus(
        IResourceStatus.INVALID_VALUE, null, message);
  }

  /* test invalid characters */
  char[] chars = OS.INVALID_RESOURCE_CHARACTERS;
  for (int i = 0; i < chars.length; i++) {
    if (segment.indexOf(chars[i]) != -1) {
      message = NLS.bind(Messages.resources_invalidCharInName, String.valueOf(chars[i]), segment);
      return new org.eclipse.core.internal.resources.ResourceStatus(
          IResourceStatus.INVALID_VALUE, null, message);
    }
  }

  /* test invalid OS names */
  if (!OS.isNameValid(segment)) {
    message = NLS.bind(Messages.resources_invalidName, segment);
    return new org.eclipse.core.internal.resources.ResourceStatus(
        IResourceStatus.INVALID_VALUE, null, message);
  }
  return Status.OK_STATUS;
}
 
Example 19
Project: che   File: Workspace.java   Source Code and License 5 votes vote down vote up
@Override
public IStatus validatePath(String path, int type) {
  /* path must not be null */
  if (path == null) {
    String message = Messages.resources_pathNull;
    return new org.eclipse.core.internal.resources.ResourceStatus(
        IResourceStatus.INVALID_VALUE, null, message);
  }
  return validatePath(Path.fromOSString(path), type, false);
}
 
Example 20
Project: che   File: Resource.java   Source Code and License 5 votes vote down vote up
/**
 * Checks that this resource exists. If checkType is true, the type of this resource and the one
 * in the tree must match.
 *
 * @exception CoreException if this resource does not exist
 */
public void checkExists(int flags, boolean checkType) throws CoreException {
  if (!exists(flags, checkType)) {
    String message = NLS.bind(Messages.resources_mustExist, getFullPath());
    throw new ResourceException(IResourceStatus.RESOURCE_NOT_FOUND, getFullPath(), message, null);
  }
}
 
Example 21
Project: che   File: ResourceTraversal.java   Source Code and License 5 votes vote down vote up
/**
 * Visits all existing resources defined by this traversal.
 *
 * @param visitor a resource visitor
 * @exception CoreException if this method fails. Reasons include:
 *     <ul>
 *       <li>The visitor failed with this exception.
 *     </ul>
 */
public void accept(IResourceVisitor visitor) throws CoreException {
  for (int i = 0, imax = resources.length; i < imax; i++)
    try {
      if (resources[i].exists()) resources[i].accept(visitor, depth, flags);
    } catch (CoreException e) {
      // ignore failure in the case of concurrent deletion
      if (e.getStatus().getCode() != IResourceStatus.RESOURCE_NOT_FOUND) throw e;
    }
}
 
Example 22
Project: che   File: Resources.java   Source Code and License 5 votes vote down vote up
private static IStatus addOutOfSync(IStatus status, IResource resource) {
  IStatus entry =
      new Status(
          IStatus.ERROR,
          ResourcesPlugin.PI_RESOURCES,
          IResourceStatus.OUT_OF_SYNC_LOCAL,
          Messages.format(
              CorextMessages.Resources_outOfSync,
              BasicElementLabels.getPathLabel(resource.getFullPath(), false)),
          null);
  if (status == null) {
    return entry;
  } else if (status.isMultiStatus()) {
    ((MultiStatus) status).add(entry);
    return status;
  } else {
    MultiStatus result =
        new MultiStatus(
            ResourcesPlugin.PI_RESOURCES,
            IResourceStatus.OUT_OF_SYNC_LOCAL,
            CorextMessages.Resources_outOfSyncResources,
            null);
    result.add(status);
    result.add(entry);
    return result;
  }
}
 
Example 23
Project: che   File: JavaModelOperation.java   Source Code and License 5 votes vote down vote up
/** Convenience method to run an operation within this operation */
public void executeNestedOperation(JavaModelOperation operation, int subWorkAmount)
    throws JavaModelException {
  IJavaModelStatus status = operation.verify();
  if (!status.isOK()) {
    throw new JavaModelException(status);
  }
  IProgressMonitor subProgressMonitor = getSubProgressMonitor(subWorkAmount);
  // fix for 1FW7IKC, part (1)
  try {
    operation.setNested(true);
    operation.run(subProgressMonitor);
  } catch (CoreException ce) {
    if (ce instanceof JavaModelException) {
      throw (JavaModelException) ce;
    } else {
      // translate the core exception to a java model exception
      if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
        Throwable e = ce.getStatus().getException();
        if (e instanceof JavaModelException) {
          throw (JavaModelException) e;
        }
      }
      throw new JavaModelException(ce);
    }
  }
}
 
Example 24
Project: che   File: JavaModelOperation.java   Source Code and License 5 votes vote down vote up
/**
 * Main entry point for Java Model operations. Runs a Java Model Operation as an
 * IWorkspaceRunnable if not read-only.
 */
public void runOperation(IProgressMonitor monitor) throws JavaModelException {
  IJavaModelStatus status = verify();
  if (!status.isOK()) {
    throw new JavaModelException(status);
  }
  try {
    if (isReadOnly()) {
      run(monitor);
    } else {
      // Use IWorkspace.run(...) to ensure that resource changes are batched
      // Note that if the tree is locked, this will throw a CoreException, but this is ok
      // as this operation is modifying the tree (not read-only) and a CoreException will be
      // thrown anyway.
      //				ResourcesPlugin.getWorkspace().run(this, getSchedulingRule(), IWorkspace.AVOID_UPDATE,
      // monitor);
      // todo use ResourcesPlugin.getWorkspace().run
      run(monitor);
    }
  } catch (CoreException ce) {
    if (ce instanceof JavaModelException) {
      throw (JavaModelException) ce;
    } else {
      if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
        Throwable e = ce.getStatus().getException();
        if (e instanceof JavaModelException) {
          throw (JavaModelException) e;
        }
      }
      throw new JavaModelException(ce);
    }
  }
}
 
Example 25
Project: che   File: Resources.java   Source Code and License 5 votes vote down vote up
private static IStatus addOutOfSync(IStatus status, IResource resource) {
  IStatus entry =
      new Status(
          IStatus.ERROR,
          ResourcesPlugin.PI_RESOURCES,
          IResourceStatus.OUT_OF_SYNC_LOCAL,
          Messages.format(
              RefactoringCoreMessages.Resources_outOfSync,
              BasicElementLabels.getPathLabel(resource.getFullPath(), false)),
          null);
  if (status == null) {
    return entry;
  } else if (status.isMultiStatus()) {
    ((MultiStatus) status).add(entry);
    return status;
  } else {
    MultiStatus result =
        new MultiStatus(
            ResourcesPlugin.PI_RESOURCES,
            IResourceStatus.OUT_OF_SYNC_LOCAL,
            RefactoringCoreMessages.Resources_outOfSyncResources,
            null);
    result.add(status);
    result.add(entry);
    return result;
  }
}
 
Example 26
Project: chromedevtools   File: ChromiumDebugPluginUtil.java   Source Code and License 5 votes vote down vote up
private static <C> IFile createFile(final C container, final FileContainerHandler<C> handler,
    String filename) {
  String patchedName = FILE_NAME_BAD_CHARS.matcher(filename).replaceAll("_");
  // In Linux and Mac it should be enough. However, lets check more.
  if (!ResourcesPlugin.getWorkspace().validateName(patchedName, IResource.FILE).isOK()) {
    patchedName = FILE_NAME_BAD_CHARS_FALLBACK.matcher(filename).replaceAll("_");
  }

  UniqueKeyGenerator.Factory<IFile> factory =
      new UniqueKeyGenerator.Factory<IFile>() {
    public IFile tryCreate(String uniqueName) {
      String filePathname = uniqueName + CHROMIUM_EXTENSION_SUFFIX;
      IFile file = handler.getFile(container, filePathname);
      if (file.exists()) {
        return null;
      }
      try {
        file.create(new ByteArrayInputStream("".getBytes()), false, null); //$NON-NLS-1$
      } catch (CoreException e) {
        IStatus status = e.getStatus();
        if (status instanceof IResourceStatus) {
          if (status.getCode() == IResourceStatus.CASE_VARIANT_EXISTS) {
            // File with different name case already exists.
            // For our case it's the same as "file.exists()".
            return null;
          }
        }
        throw new RuntimeException(e);
      }
      return file;
    }
  };

  // Can we have 1000 same-named files?
  return UniqueKeyGenerator.createUniqueKey(patchedName, 1000, factory);
}
 
Example 27
Project: APICloud-Studio   File: TeamAction.java   Source Code and License 5 votes vote down vote up
/**
 * Method invoked from <code>selectionChanged(IAction, ISelection)</code> 
 * to set the enablement status of the action. The instance variable 
 * <code>selection</code> will contain the latest selection so the methods
 * <code>getSelectedResources()</code> and <code>getSelectedProjects()</code>
 * will provide the proper objects.
 * 
 * This method can be overridden by subclasses but should not be invoked by them.
 */
protected void setActionEnablement(IAction action) {
	try {
		action.setEnabled(isEnabled());
	} catch (TeamException e) {
		if (e.getStatus().getCode() == IResourceStatus.OUT_OF_SYNC_LOCAL) {
			// Enable the action to allow the user to discover the problem
			action.setEnabled(true);
		} else {
			action.setEnabled(false);
			// We should not open a dialog when determining menu enablements so log it instead
			SVNUIPlugin.log(e);
		}
	}
}
 
Example 28
Project: APICloud-Studio   File: RemoteAnnotationStorage.java   Source Code and License 5 votes vote down vote up
public String getCharset() throws CoreException {
	InputStream contents = getContents();
	try {
		String charSet = SVNUIPlugin.getCharset(getName(), contents);
		return charSet;
	} catch (IOException e) {
		throw new SVNException(new Status(IStatus.ERROR, SVNUIPlugin.ID, IResourceStatus.FAILED_DESCRIBING_CONTENTS, Policy.bind("RemoteAnnotationStorage.1", getFullPath().toString()), e)); //$NON-NLS-1$
	} finally {
		try {
			contents.close();
		} catch (IOException e1) {
			// Ignore
		}
	}
}
 
Example 29
Project: APICloud-Studio   File: ExceptionHandler.java   Source Code and License 5 votes vote down vote up
/**
 * @param e
 * @return
 */
@SuppressWarnings("unused")
private boolean isInvalidResouceName(CoreException e)
{
	IStatus status = e.getStatus();
	if (status == null)
	{
		return false;
	}
	if (!ResourcesPlugin.PI_RESOURCES.equals(status.getPlugin()))
	{
		return false;
	}
	if (status.isMultiStatus())
	{
		final IStatus[] children = status.getChildren();
		for (int i = 0; i < children.length; ++i)
		{
			final IStatus child = children[i];
			if (!(ResourcesPlugin.PI_RESOURCES.equals(status.getPlugin()) && child.getCode() == IResourceStatus.INVALID_RESOURCE_NAME))
			{
				return false;
			}
		}
		return true;
	}
	else
	{
		if (status.getCode() == IResourceStatus.INVALID_RESOURCE_NAME)
		{
			return true;
		}
	}
	return false;
}
 
Example 30
Project: sysdeotomcat   File: TomcatProject.java   Source Code and License 5 votes vote down vote up
private void createFolder(IFolder folderHandle)  throws CoreException {
	try {
		// Create the folder resource in the workspace
		folderHandle.create(false, true, null); //new SubProgressMonitor(monitor, 500));
	}
	catch (CoreException e) {
		// If the folder already existed locally, just refresh to get contents
		if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
			folderHandle.refreshLocal(IResource.DEPTH_INFINITE, null); //new SubProgressMonitor(monitor, 500));
		else
			throw e;
	}
}
 
Example 31
Project: sysdeotomcat   File: TomcatProject.java   Source Code and License 5 votes vote down vote up
private void createFile(IFile fileHandle, String content)  throws CoreException {
	try {
		fileHandle.create(new ByteArrayInputStream(content.getBytes()), 0, null);
	}
	catch (CoreException e) {
		// If the file already existed locally, just refresh to get contents
		if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED)
			fileHandle.refreshLocal(IResource.DEPTH_INFINITE, null); //new SubProgressMonitor(monitor, 500));
		else
			throw e;
	}
}
 
Example 32
Project: goclipse   File: ProblemsLabelDecorator.java   Source Code and License 5 votes vote down vote up
/**
 * Computes the adornment flags for the given element.
 *
 * @param obj the element to compute the flags for
 *
 * @return the adornment flags
 */
protected ImageDescriptor computeAdornmentFlags(Object obj) {
	try {
		if (obj instanceof IResource) {
			return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE);
		}
	} catch (CoreException e) {
		if (e.getStatus().getCode() == IResourceStatus.MARKER_NOT_FOUND) {
			return null;
		}

		EclipseCore.logStatus(e);
	}
	return null;
}
 
Example 33
Project: n4js   File: N4JSResource.java   Source Code and License 4 votes vote down vote up
/**
 *
 * Discards the current content of the resource, sets the parser result as first slot, installs derived state (this
 * will build up the second slot again) and sends notifications that proxies have been resolved. The resource will
 * be even loaded if its already marked as loaded.
 *
 * If the second slot, that is the TModule, was already loaded and we just resolved the AST, then the existing
 * TModule is kept in the resource and rewired to the resolved AST.
 *
 * @param object
 *            the object which resource should be loaded
 * @return the loaded/resolved object
 */
private EObject demandLoadResource(EObject object) {
	TModule oldModule = null;
	EObject oldScript = null;
	ModuleAwareContentsList myContents = ((ModuleAwareContentsList) contents);
	try {
		oldModule = discardStateFromDescription(false);
		if (!myContents.isEmpty()) {
			oldScript = myContents.basicGet(0);
			myContents.sneakyClear();
		}
		// now everything is removed from the resource and contents is empty
		// stop sending notifications
		eSetDeliver(false);

		if (isLoaded) {
			// Loads the resource even its marked as being already loaded
			isLoaded = false;
		}
		superLoad(null);

		// manually send the notification
		eSetDeliver(true);
		EObject result = getParseResult().getRootASTElement();
		if (myContents.isEmpty()) {
			myContents.sneakyAdd(0, result);
			if (oldModule != null) {
				myContents.sneakyAdd(oldModule);
			}
			forceInstallDerivedState(false);
		} else {
			if (myContents.size() == 1) {
				if (oldModule != null) {
					myContents.sneakyAdd(oldModule);
				}
			}
			installDerivedState(false);
		}
		if (oldScript != null) {
			notifyProxyResolved(0, oldScript);
		}
		fullyPostProcessed = false;
		return result;
	} catch (IOException | IllegalStateException ioe) {
		if (myContents.isEmpty()) {
			myContents.sneakyAdd(oldScript);
			myContents.sneakyAdd(oldModule);
		}
		Throwable cause = ioe.getCause();
		if (cause instanceof CoreException) {
			IStatus status = ((CoreException) cause).getStatus();
			if (IResourceStatus.RESOURCE_NOT_FOUND == status.getCode()) {
				return object;
			}
		}
		logger.error("Error in demandLoadResource for " + getURI(), ioe);
		return object;
	}
}
 
Example 34
Project: subclipse   File: SVNFileModificationValidator.java   Source Code and License 4 votes vote down vote up
private IStatus getDefaultStatus(IFile file) {
	return 
	    isReadOnly(file)
		? new Status(IStatus.ERROR, SVNProviderPlugin.ID, IResourceStatus.READ_ONLY_LOCAL, Policy.bind("FileModificationValidator.fileIsReadOnly", new String[] { file.getFullPath().toString() }), null) 
			: Status.OK_STATUS;
}
 
Example 35
Project: subclipse   File: SVNUIPlugin.java   Source Code and License 4 votes vote down vote up
/**
 * Convenience method for showing an error dialog 
 * @param shell a valid shell or null
 * @param exception the exception to be report
 * @param title the title to be displayed
 * @param flags customizing attributes for the error handling
 * @return IStatus the status that was displayed to the user
 */
public static IStatus openError(Shell providedShell, String title, String message, Throwable exception, int flags) {
	// Unwrap InvocationTargetExceptions
	if (exception instanceof InvocationTargetException) {
		Throwable target = ((InvocationTargetException)exception).getTargetException();
		// re-throw any runtime exceptions or errors so they can be handled by the workbench
		if (target instanceof RuntimeException) {
			throw (RuntimeException)target;
		}
		if (target instanceof Error) {
			throw (Error)target;
		} 
		return openError(providedShell, title, message, target, flags);
	}
	
	// Determine the status to be displayed (and possibly logged)
	IStatus status = null;
	boolean log = false;
	if (exception instanceof CoreException) {
		status = ((CoreException)exception).getStatus();
		log = ((flags & LOG_CORE_EXCEPTIONS) > 0);
	} else if (exception instanceof TeamException) {
		status = ((TeamException)exception).getStatus();
		log = ((flags & LOG_TEAM_EXCEPTIONS) > 0);
	} else if (exception instanceof InterruptedException) {
		return new SVNStatus(IStatus.OK, Policy.bind("ok")); //$NON-NLS-1$
	} else if (exception != null) {
		status = new SVNStatus(IStatus.ERROR, Policy.bind("internal"), exception); //$NON-NLS-1$
		log = ((flags & LOG_OTHER_EXCEPTIONS) > 0);
		if (title == null) title = Policy.bind("SimpleInternal"); //$NON-NLS-1$
	}
	
	// Check for a build error and report it differently
	if (status.getCode() == IResourceStatus.BUILD_FAILED) {
		message = Policy.bind("buildError"); //$NON-NLS-1$
		log = true;
	}
	
	// Check for multi-status with only one child
	if (status.isMultiStatus() && status.getChildren().length == 1) {
		status = status.getChildren()[0];
	}
	if (status.isOK()) return status;
	
	// Log if the user requested it
	if (log) SVNUIPlugin.log(status);
	// Create a runnable that will display the error status
	
	String svnInterface = SVNUIPlugin.getPlugin().getPreferenceStore().getString(ISVNUIConstants.PREF_SVNINTERFACE);
	boolean loadError = svnInterface.equals("javahl") && status != null && status.getMessage() != null && status.getMessage().equals(SVNClientManager.UNABLE_TO_LOAD_DEFAULT_CLIENT);
	
	if (!loadError || loadErrorHandled) {
		final String displayTitle = title;
		final String displayMessage = message;
		final IStatus displayStatus = status;
		final IOpenableInShell openable = new IOpenableInShell() {
			public void open(Shell shell) {
				if (displayStatus.getSeverity() == IStatus.INFO && !displayStatus.isMultiStatus()) {
					MessageDialog.openInformation(shell, Policy.bind("information"), displayStatus.getMessage()); //$NON-NLS-1$
				} else {
					ErrorDialog.openError(shell, displayTitle, displayMessage, displayStatus);
				}
			}
		};
		openDialog(providedShell, openable, flags);
	}
	
	if (loadError) loadErrorHandled = true;
	
	// return the status we display
	return status;
}
 
Example 36
Project: che   File: Resource.java   Source Code and License 4 votes vote down vote up
/**
 * Calls the move/delete hook to perform the move. Since this method calls client code, it is run
 * "unprotected", so the workspace lock is not held. Returns true if resources were actually
 * moved, and false otherwise.
 */
private boolean unprotectedMove(
    final IResource destination, int updateFlags, IProgressMonitor monitor)
    throws CoreException, ResourceException {
  //        IMoveDeleteHook hook = workspace.getMoveDeleteHook();
  switch (getType()) {
    case IResource.FILE:
      //                if (!hook.moveFile(tree, (IFile) this, (IFile) destination, updateFlags,
      // Policy.subMonitorFor(monitor, Policy.opWork / 2)))
      workspace.standardMoveFile(
          (IFile) this,
          (IFile) destination,
          updateFlags,
          Policy.subMonitorFor(monitor, Policy.opWork));
      break;
    case IResource.FOLDER:
      //                if (!hook.moveFolder(tree, (IFolder) this, (IFolder) destination,
      // updateFlags, Policy.subMonitorFor(monitor, Policy.opWork / 2)))
      workspace.standardMoveFolder(
          (IFolder) this,
          (IFolder) destination,
          updateFlags,
          Policy.subMonitorFor(monitor, Policy.opWork));
      break;
    case IResource.PROJECT:
      IProject project = (IProject) this;
      // if there is no change in name, there is nothing to do so return.
      if (getName().equals(destination.getName())) return false;
      IProjectDescription description = project.getDescription();
      description.setName(destination.getName());
      //                if (!hook.moveProject(tree, project, description, updateFlags,
      // Policy.subMonitorFor(monitor, Policy.opWork / 2)))
      workspace.standardMoveProject(
          project, description, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork));
      break;
    case IResource.ROOT:
      String msg = Messages.resources_moveRoot;
      throw new ResourceException(
          new ResourceStatus(IResourceStatus.INVALID_VALUE, getFullPath(), msg));
  }
  return true;
}
 
Example 37
Project: che   File: FileDescription.java   Source Code and License 4 votes vote down vote up
public void createExistentResourceFromHandle(IResource resource, IProgressMonitor monitor)
    throws CoreException {

  Assert.isLegal(resource instanceof IFile);
  if (resource.exists()) {
    return;
  }
  IFile fileHandle = (IFile) resource;
  monitor.beginTask("", 200); // $NON-NLS-1$
  monitor.setTaskName(UndoMessages.FileDescription_NewFileProgress);
  try {
    if (monitor.isCanceled()) {
      throw new OperationCanceledException();
    }
    if (location != null) {
      fileHandle.createLink(
          location, IResource.ALLOW_MISSING_LOCAL, new SubProgressMonitor(monitor, 200));
    } else {
      InputStream contents =
          new ByteArrayInputStream(
              UndoMessages.FileDescription_ContentsCouldNotBeRestored.getBytes());
      // Retrieve the contents from the file content
      // description. Other file state attributes, such as timestamps,
      // have already been retrieved from the original IResource
      // object and are restored in #restoreResourceAttributes
      if (fileContentDescription != null && fileContentDescription.exists()) {
        contents = fileContentDescription.getContents();
      }
      fileHandle.create(contents, false, new SubProgressMonitor(monitor, 100));
      fileHandle.setCharset(charset, new SubProgressMonitor(monitor, 100));
    }
    if (monitor.isCanceled()) {
      throw new OperationCanceledException();
    }
  } catch (CoreException e) {
    if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED) {
      fileHandle.refreshLocal(IResource.DEPTH_ZERO, null);
    } else {
      throw e;
    }
  } finally {
    monitor.done();
  }
}
 
Example 38
Project: che   File: FileUndoState.java   Source Code and License 4 votes vote down vote up
public void createExistentResourceFromHandle(IResource resource, IProgressMonitor monitor)
    throws CoreException {

  Assert.isLegal(resource instanceof IFile);
  if (resource.exists()) {
    return;
  }
  IFile fileHandle = (IFile) resource;
  monitor.beginTask("", 200); // $NON-NLS-1$
  monitor.setTaskName(RefactoringCoreMessages.FileDescription_NewFileProgress);
  try {
    if (monitor.isCanceled()) {
      throw new OperationCanceledException();
    }
    if (location != null) {
      fileHandle.createLink(
          location, IResource.ALLOW_MISSING_LOCAL, new SubProgressMonitor(monitor, 200));
    } else {
      InputStream contents =
          new ByteArrayInputStream(
              RefactoringCoreMessages.FileDescription_ContentsCouldNotBeRestored.getBytes());
      // Retrieve the contents from the file content
      // description. Other file state attributes, such as timestamps,
      // have already been retrieved from the original IResource
      // object and are restored in #restoreResourceAttributes
      if (fileContentDescription != null && fileContentDescription.exists()) {
        contents = fileContentDescription.getContents();
      }
      fileHandle.create(contents, false, new SubProgressMonitor(monitor, 100));
      fileHandle.setCharset(charset, new SubProgressMonitor(monitor, 100));
    }
    if (monitor.isCanceled()) {
      throw new OperationCanceledException();
    }
  } catch (CoreException e) {
    if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED) {
      fileHandle.refreshLocal(IResource.DEPTH_ZERO, null);
    } else {
      throw e;
    }
  } finally {
    monitor.done();
  }
}
 
Example 39
Project: APICloud-Studio   File: SVNUIPlugin.java   Source Code and License 4 votes vote down vote up
/**
 * Convenience method for showing an error dialog 
 * @param shell a valid shell or null
 * @param exception the exception to be report
 * @param title the title to be displayed
 * @param flags customizing attributes for the error handling
 * @return IStatus the status that was displayed to the user
 */
public static IStatus openError(Shell providedShell, String title, String message, Throwable exception, int flags) {
	// Unwrap InvocationTargetExceptions
	if (exception instanceof InvocationTargetException) {
		Throwable target = ((InvocationTargetException)exception).getTargetException();
		// re-throw any runtime exceptions or errors so they can be handled by the workbench
		if (target instanceof RuntimeException) {
			throw (RuntimeException)target;
		}
		if (target instanceof Error) {
			throw (Error)target;
		} 
		return openError(providedShell, title, message, target, flags);
	}
	
	// Determine the status to be displayed (and possibly logged)
	IStatus status = null;
	boolean log = false;
	if (exception instanceof CoreException) {
		status = ((CoreException)exception).getStatus();
		log = ((flags & LOG_CORE_EXCEPTIONS) > 0);
	} else if (exception instanceof TeamException) {
		status = ((TeamException)exception).getStatus();
		log = ((flags & LOG_TEAM_EXCEPTIONS) > 0);
	} else if (exception instanceof InterruptedException) {
		return new SVNStatus(IStatus.OK, Policy.bind("ok")); //$NON-NLS-1$
	} else if (exception != null) {
		status = new SVNStatus(IStatus.ERROR, Policy.bind("internal"), exception); //$NON-NLS-1$
		log = ((flags & LOG_OTHER_EXCEPTIONS) > 0);
		if (title == null) title = Policy.bind("SimpleInternal"); //$NON-NLS-1$
	}
	
	// Check for a build error and report it differently
	if (status.getCode() == IResourceStatus.BUILD_FAILED) {
		message = Policy.bind("buildError"); //$NON-NLS-1$
		log = true;
	}
	
	// Check for multi-status with only one child
	if (status.isMultiStatus() && status.getChildren().length == 1) {
		status = status.getChildren()[0];
	}
	if (status.isOK()) return status;
	
	// Log if the user requested it
	if (log) SVNUIPlugin.log(status);
	// Create a runnable that will display the error status
	
	String svnInterface = SVNUIPlugin.getPlugin().getPreferenceStore().getString(ISVNUIConstants.PREF_SVNINTERFACE);
	boolean loadError = svnInterface.equals("javahl") && status != null && status.getMessage() != null && status.getMessage().equals(SVNClientManager.UNABLE_TO_LOAD_DEFAULT_CLIENT);
	
	if (!loadError || loadErrorHandled) {
		final String displayTitle = title;
		final String displayMessage = message;
		final IStatus displayStatus = status;
		final IOpenableInShell openable = new IOpenableInShell() {
			public void open(Shell shell) {
				if (displayStatus.getSeverity() == IStatus.INFO && !displayStatus.isMultiStatus()) {
					MessageDialog.openInformation(shell, Policy.bind("information"), displayStatus.getMessage()); //$NON-NLS-1$
				} else {
					ErrorDialog.openError(shell, displayTitle, displayMessage, displayStatus);
				}
			}
		};
		openDialog(providedShell, openable, flags);
	}
	
	if (loadError) loadErrorHandled = true;
	
	// return the status we display
	return status;
}
 
Example 40
Project: APICloud-Studio   File: SVNFileModificationValidator.java   Source Code and License 4 votes vote down vote up
private IStatus getDefaultStatus(IFile file) {
	return 
	    isReadOnly(file)
		? new Status(IStatus.ERROR, SVNProviderPlugin.ID, IResourceStatus.READ_ONLY_LOCAL, Policy.bind("FileModificationValidator.fileIsReadOnly", new String[] { file.getFullPath().toString() }), null) 
			: Status.OK_STATUS;
}