Java 类org.eclipse.core.resources.IResource 实例源码

项目:eclipse-batch-editor    文件:BatchEditor.java   
private int getSeverity() {
    IEditorInput editorInput = getEditorInput();
    if (editorInput == null) {
        return IMarker.SEVERITY_INFO;
    }
    try {
        final IResource resource = ResourceUtil.getResource(editorInput);
        if (resource == null) {
            return IMarker.SEVERITY_INFO;
        }
        int severity = resource.findMaxProblemSeverity(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
        return severity;
    } catch (CoreException e) {
        // Might be a project that is not open
    }
    return IMarker.SEVERITY_INFO;
}
项目:eclipse-commons    文件:TestToIResourcePositive.java   
@Test
public void fileNested() throws Exception {
    waitForWorkspaceChanges(() -> {
        project.getFolder("/folder").create(true, true, null);
        project.getFolder("/folder/deep/").create(true, true, null);
        IFile file = project.getFile("/folder/deep/myFile.ext");
        file.create(new NullInputStream(0), true, null);
    });

    URI uri = URI.createPlatformResourceURI("/myProject/folder/deep/myFile.ext", true);
    IResource iResource = UriUtils.toIResource(uri);

    assertTrue(iResource instanceof IFile);
    assertTrue(iResource.exists());
    assertEquals("/myProject/folder/deep/myFile.ext", iResource.getFullPath().toString());
}
项目:gw4e.project    文件:BuildPoliciesCache.java   
/**
 * @param projectName
 * @param container
 * @param monitor
 */
private static void deleteCache(String cachename, IContainer container, IProgressMonitor monitor) {
    try {
        IResource[] members = container.members();
        for (IResource member : members) {
            if (member instanceof IContainer) {
                deleteCache(cachename, (IContainer) member, monitor);
            } else if (member instanceof IFile) {
                IFile file = (IFile) member;
                if (cachename.equals(file.getName())) {
                    file.delete(true, monitor);
                }
            }
        }
    } catch (CoreException e) {
        ResourceManager.logException(e);
    }
}
项目:Hydrograph    文件:FilterOperationClassUtility.java   
/**
 * @param filterExtension
 * @param fileName
 * Open the dialog to browse .xml file for expression, operation or outputfields
 */
private void browseXMLSelectionDialog(String filterExtension, Text fileName) {
    String externalSchemaTextBoxValue = "";
    ExternalSchemaFileSelectionDialog dialog = new ExternalSchemaFileSelectionDialog("Project",
            "Select Input File (.xml)",  new String[]{filterExtension,Extensions.XML.toString()}, this);
    if (dialog.open() == IDialogConstants.OK_ID) {
        String file = fileNameTextBoxValue;
        IResource resource = (IResource) dialog.getFirstResult();
        String path[] = resource.getFullPath().toString().split("/");
        if (file.isEmpty()) {
            for (int i = 1; i < path.length; i++) {
                externalSchemaTextBoxValue = externalSchemaTextBoxValue + path[i] + "/";
            }
        } else {
            for (int i = 1; i < path.length; i++) {
                if (!path[i].endsWith(".xml")) {
                    externalSchemaTextBoxValue = externalSchemaTextBoxValue + path[i] + "/";
                }
            }
            externalSchemaTextBoxValue = externalSchemaTextBoxValue + file;
        }
        fileName.setText(externalSchemaTextBoxValue);
    }
}
项目:visuflow-plugin    文件:WizardPageHandler.java   
/**
 * This method ensures user select Target project and permissions
 */
private void dialogChanged() {
    IResource container = ResourcesPlugin.getWorkspace().getRoot()
            .findMember(new Path(getContainerName().get("TargetPath")));


    if (getContainerName().get("TargetPath").length() == 0) {
        updateStatus("File container must be specified");
        return;
    }
    if (container == null
            || (container.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) {
        updateStatus("File container must exist");
        return;
    }
    if (!container.isAccessible()) {
        updateStatus("Project must be writable");
        return;
    }
    updateStatus(null);
}
项目:n4js    文件:ProjectSelectionDialog.java   
@Override
public Object[] getElements(Object inputElement) {
    if (inputElement instanceof IContainer) {
        try {
            List<IResource> projects = Arrays.asList(((IContainer) inputElement).members()).stream()
                    .filter(member -> member instanceof IProject)
                    .filter(project -> isN4JSProject((IProject) project))
                    .sorted(new ResourceComparator())
                    .collect(Collectors.toList());

            return projects.toArray(new IResource[projects.size()]);

        } catch (CoreException e) {
            e.printStackTrace();
            return null;
        }
    }
    return null;
}
项目:gw4e.project    文件:ResourceManager.java   
/**
 * Process recursively the containers until we found a resource with the
 * specified path
 * 
 * @param container
 * @param path
 * @return
 * @throws CoreException
 */
private static boolean resourceExistsIn(IContainer container, IPath path) throws CoreException {
    boolean found = false;
    IResource[] members = container.members();
    for (IResource member : members) {
        if (member instanceof IContainer) {

            found = resourceExistsIn((IContainer) member, path);
            if (found)
                break;
        } else if (member instanceof IFile) {
            IFile file = (IFile) member;

            if (path.equals(file.getFullPath()))
                return true;
        }
    }
    return found;
}
项目:solidity-ide    文件:SolidityCompilerBase.java   
@Override
public void compile(List<URI> uris, IProgressMonitor progress) {
    Set<IResource> filesToCompile = getFilesToCompile(uris);
    if (filesToCompile.isEmpty() || progress.isCanceled()) {
        return;
    }
    progress.beginTask("compiling ...", filesToCompile.size());
    try {
        Process process = new ProcessBuilder(getCompilerPath(), "--standard-json").start();
        sendInput(process.getOutputStream(), filesToCompile);
        handler.handleOutput(process.getInputStream(), filesToCompile);
        if (process.waitFor(30, TimeUnit.SECONDS) && process.exitValue() != 0) {
            throw new Exception("Solidity compiler invocation failed with exit code " + process.exitValue() + ".");
        }
        progress.done();

    } catch (Exception e) {
        e.printStackTrace();
        progress.done();
    }

}
项目:Equella    文件:JPFManifestBuilder.java   
@Override
public boolean visit(IResourceDelta delta) throws CoreException
{
    IResource resource = delta.getResource();
    if( resource.isDerived() )
    {
        return false;
    }
    if( resource.getType() == IResource.FILE )
    {
        IFile file = (IFile) resource;
        IProject project = resource.getProject();
        if( file.equals(JPFProject.getManifest(project)) )
        {
            manifestChanged = true;
            return false;
        }
    }
    return true;
}
项目:gemoc-studio-modeldebugging    文件:SiriusEditorUtils.java   
/**
 * Show the given {@link EObject instruction}.
 * 
 * @param editorPart
 *            the opened {@link DialectEditor}
 * @param instruction
 *            the {@link EObject instruction} to show
 */
public static void showInstruction(DialectEditor editorPart, EObject instruction) {
    final URI resourceURI = instruction.eResource().getURI();
    if (resourceURI.isPlatformResource()) {
        final String resourcePath = resourceURI.toPlatformString(true);
        final IResource resource = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(
                resourcePath));
        try {
            final IMarker marker = resource.createMarker(EValidator.MARKER);
            marker.setAttribute(EValidator.URI_ATTRIBUTE, EcoreUtil.getURI(instruction).toString());
            final TraceabilityMarkerNavigationProvider navigationProvider = new TraceabilityMarkerNavigationProvider(
                    (DialectEditor)editorPart);
            navigationProvider.gotoMarker(marker);
            marker.delete();
        } catch (CoreException e) {
            DebugSiriusIdeUiPlugin.INSTANCE.log(e);
        }
    }
}
项目:Hydrograph    文件:JobDeleteParticipant.java   
private void setJobFileAndXmlFile(IFolder jobsFolder) {
    try {
        IResource[] members = jobsFolder.members();
        if (members != null) {
            for (IResource jobFolderMember : members) {
                if ((IFolder.class).isAssignableFrom(jobFolderMember.getClass())) {
                    setJobFileAndXmlFile((IFolder) jobFolderMember);
                } else if ((IFile.class).isAssignableFrom(jobFolderMember.getClass())) {
                    String file = jobFolderMember.getFullPath().lastSegment();
                    if (StringUtils.equalsIgnoreCase(modifiedResource.getName().replace(Constants.PROPERTIES_EXTENSION,
                            Constants.JOB_EXTENSION), file)) {
                        jobIFile = jobsFolder.getFile(modifiedResource.getName()
                                .replace(Constants.PROPERTIES_EXTENSION, Constants.JOB_EXTENSION));
                    } else if (StringUtils.equalsIgnoreCase(modifiedResource.getName().replace(Constants.PROPERTIES_EXTENSION,
                            Constants.XML_EXTENSION), file)) {
                        xmlIFile = jobsFolder.getFile(modifiedResource.getName()
                                .replace(Constants.PROPERTIES_EXTENSION, Constants.XML_EXTENSION));
                    }
                }
            }
        }
    } catch (CoreException coreException) {
        LOGGER.error("Error while setting job file and xml file for dependent deletion", coreException);
    }
}
项目:gw4e.project    文件:GW4EBuilder.java   
/**
 * @param project
 * @param file
 */
public static void removeMarkerForAbstractContextUsed (IFile file) {
    try {
        IMarker[] markers = file.findMarkers(GW4EBuilder.MARKER_TYPE, true, IResource.DEPTH_INFINITE);
        for (int i = 0; i < markers.length; i++) {
            IMarker m = markers[i];
            Integer pbId = (Integer)m.getAttribute(IJavaModelMarker.ID);
            if (pbId!=null) {
                if (GW4EParser.ABSTRACT_CONTEXT_USED==pbId.intValue()) {
                    m.delete();
                }
            }
        }
    } catch (CoreException ce) {
    }
}
项目:n4js    文件:CleanInstruction.java   
private void cleanOutput(IProject aProject, OutputConfiguration config, IProgressMonitor monitor)
        throws CoreException {
    IContainer container = getContainer(aProject, config.getOutputDirectory());
    if (!container.exists()) {
        return;
    }
    if (config.isCanClearOutputDirectory()) {
        for (IResource resource : container.members()) {
            resource.delete(IResource.KEEP_HISTORY, monitor);
        }
    } else if (config.isCleanUpDerivedResources()) {
        List<IFile> resources = derivedResourceMarkers.findDerivedResources(container, null);
        for (IFile iFile : resources) {
            iFile.delete(IResource.KEEP_HISTORY, monitor);
        }
    }
}
项目:Tarski    文件:CountMarkersInResourceHandler.java   
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
  ISelection selection = MarkerFactory.getSelection();
  if (selection instanceof ITreeSelection) {
    ITreeSelection treeSelection = (ITreeSelection) selection;
    if (treeSelection.getFirstElement() instanceof IOpenable
        || treeSelection.getFirstElement() instanceof IFile) {
      IResource resource =
          ((IAdaptable) treeSelection.getFirstElement()).getAdapter(IResource.class);
      List<IMarker> markers = MarkerFactory.findMarkers(resource);
      MessageDialog dialog = new MessageDialog(MarkerActivator.getShell(), "Marker Count", null,
          markers.size() + " marker(s)", MessageDialog.INFORMATION, new String[] {"OK"}, 0);
      dialog.open();
    }
  }
  return null;
}
项目:gw4e.project    文件:JDTManager.java   
public static ICompilationUnit[] getOrCreateGeneratedTestInterfaces(IProject project)
        throws CoreException, FileNotFoundException {

    project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
    IPath folderForMain = project.getFullPath()
            .append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), true));
    IPath folderForTest = project.getFullPath()
            .append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), false));
    if (ResourceManager.getResource(folderForMain.toString()) == null
            && ResourceManager.getResource(folderForTest.toString()) == null) {
        throw new IllegalStateException(
                "No target/generated-sources or target/generated-test-sources folders found");
    }



    // In main resource folder
    ICompilationUnit[] inMain = getExistingGeneratedTestInterfaces(project, true);
    // In test resource folder
    ICompilationUnit[] inTest = getExistingGeneratedTestInterfaces(project, false);
    ICompilationUnit[] ret = new ICompilationUnit[inMain.length+inTest.length];
    System.arraycopy(inMain, 0, ret, 0, inMain.length);
    System.arraycopy(inTest, 0, ret, inMain.length, inTest.length);
    return ret;
}
项目:dsp4e    文件:DSPDebugTarget.java   
private void addBreakpointToMap(IBreakpoint breakpoint) throws CoreException {
    Assert.isTrue(supportsBreakpoint(breakpoint) && breakpoint instanceof ILineBreakpoint);
    if (breakpoint instanceof ILineBreakpoint) {
        ILineBreakpoint lineBreakpoint = (ILineBreakpoint) breakpoint;
        IResource resource = lineBreakpoint.getMarker().getResource();
        IPath location = resource.getLocation();
        String path = location.toOSString();
        String name = location.lastSegment();
        int lineNumber = lineBreakpoint.getLineNumber();

        Source source = new Source().setName(name).setPath(path);

        List<SourceBreakpoint> sourceBreakpoints = targetBreakpoints.computeIfAbsent(source,
                s -> new ArrayList<>());
        sourceBreakpoints.add(new SourceBreakpoint().setLine(lineNumber));
    }
}
项目:EclipseMinifyBuilder    文件:PrefsAccess.java   
/**
 * Remove a resource (i.e. all its properties) from the builder's preferences.
 * 
 * @param prefs the preferences
 * @param resource the resource
 * @throws BackingStoreException
 */
public static void removeResource(Preferences prefs, IResource resource) 
        throws CoreException {
    try {
        String[] keys = prefs.keys();
        for (String key: keys) {
            if (key.endsWith("//" + resource.getProjectRelativePath().toPortableString())) {
                prefs.remove(key);
            }
        }
        prefs.flush();
    } catch (BackingStoreException e) {
        throw new CoreException(new Status(
                IStatus.ERROR, MinifyBuilder.BUILDER_ID, e.getMessage(), e));
    }
}
项目:ec4e    文件:EditorConfigSearchQuery.java   
@Override
public IStatus run(IProgressMonitor monitor) throws OperationCanceledException {
    startTime = System.currentTimeMillis();
    AbstractTextSearchResult textResult = (AbstractTextSearchResult) getSearchResult();
    textResult.removeAll();

    try {

        IContainer dir = configFile.getParent();
        dir.accept(new AbstractSectionPatternVisitor(section) {

            @Override
            protected void collect(IResourceProxy proxy) {
                Match match = new FileMatch((IFile) proxy.requestResource());
                result.addMatch(match);
            }
        }, IResource.NONE);

        return Status.OK_STATUS;
    } catch (Exception ex) {
        return new Status(IStatus.ERROR, EditorConfigPlugin.PLUGIN_ID, ex.getMessage(), ex);
    }
}
项目:gw4e.project    文件:PreferenceManager.java   
/**
 * Return the allowed folder where test can be generated in depending on the
 * user selection if the selected graph is in src/main/resource then
 * src/main/java if the selected graph is in src/test/resource then
 * src/test/java
 * 
 * @return
 */
public static IPath getTargetFolderForGeneratedTests(IResource selectedGraphFile) {

    IProject project = selectedGraphFile.getProject();

    IPath pathResourceTestFolder = project.getFullPath().append(getTestResourceFolder());
    if (ResourceManager.isInFolder(pathResourceTestFolder,
            selectedGraphFile.getParent().getFullPath()))
        return project.getFullPath().append(getTestSourceFolder());

    IPath pathResourceMainFolder = project.getFullPath().append(getMainResourceFolder());
    if (ResourceManager.isInFolder(pathResourceMainFolder,
            selectedGraphFile.getParent().getFullPath()))
        return project.getFullPath().append(getMainSourceFolder());
    return null;
}
项目:neoscada    文件:ProjectBuilder.java   
protected void validateAll ( final IProject project, final ComposedAdapterFactory adapterFactory, final Set<String> extensions, final IProgressMonitor monitor )
{
    logger.debug ( "Validating all resources of {}", project );

    try
    {
        project.accept ( new IResourceVisitor () {

            @Override
            public boolean visit ( final IResource resource ) throws CoreException
            {
                return handleResource ( null, resource, adapterFactory, extensions, monitor );
            }
        } );
    }
    catch ( final CoreException e )
    {
        StatusManager.getManager ().handle ( e.getStatus () );
    }
}
项目:pgcodekeeper    文件:PgDecorator.java   
@Override
public void decorate(Object element, IDecoration decoration) {
    if (element instanceof IResource) {
        IResource res = (IResource) element;
        IProject proj = res.getProject();
        try {
            if (proj != null && proj.isAccessible() && proj.hasNature(NATURE.ID)) {
                IMarker[] markers = res.findMarkers(MARKER.ERROR, false,
                        IResource.DEPTH_INFINITE);
                if (markers.length > 0) {
                    decoration.addOverlay(PlatformUI.getWorkbench().getSharedImages()
                            .getImageDescriptor(ISharedImages.IMG_DEC_FIELD_ERROR));
                }
            }
        } catch (CoreException e) {
            Log.log(e);
        }
    }
}
项目:SimQRI    文件:WorkspaceManager.java   
/**
 * 
 * @param modelingProject the name of the selected modeling project
 * @return the list of all the report templates name that are available in the selected modeling project
 */
public static List<String> getTemplates(String modelingProject) { // For the SimulationManagementWindow (names)
    List<String> templatesName = new ArrayList<String>();
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(modelingProject);
    IFolder templatesFolder = project.getFolder("Report Templates");
    try {
        IResource[] folderContent = templatesFolder.members();
        for(IResource resource : folderContent) {
            if(resource.getType() == IFile.FILE && resource.getFileExtension().equals("rptdesign")) {
                templatesName.add(resource.getName());
            }
        }
    } catch (CoreException e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "Error: " + e.getMessage() + "", "Error", JOptionPane.ERROR_MESSAGE);
    }
    return templatesName;
}
项目:Tarski    文件:MarkerFactory.java   
/**
 * Finds a marker for given selection on the tree
 *
 * @param treeSelection
 * @param resource
 * @return
 */
public static IMarker findMarkerByTreeSelection(final ITreeSelection treeSelection,
    final IResource resource) {
  final Object o = treeSelection.getFirstElement();
  if (o != null && o instanceof EObject) {
    final String uri = EcoreUtil.getURI((EObject) o).toString();

    final List<IMarker> markers = MarkerFactory.findMarkers(resource);

    for (final IMarker iMarker : markers) {
      if (uri.equals(MarkUtilities.getUri(iMarker))) {
        return iMarker;
      }
    }
  }
  return null;
}
项目:solidity-ide    文件:SolidityMarkerCreator.java   
private SolcIssue createSolcIssue(CompileError error, Set<IResource> filesToCompile) {
    String[] parts = error.getFormattedMessage().split(":");
    String fileName = partAtIndex(parts, 0);
    IFile errorFile = findFileForName(filesToCompile, fileName);
    int lineNumber = extractNumber(partAtIndex(parts, 1));
    int columnNumber = extractNumber(partAtIndex(parts, 2));
    Map<Integer, String> fileContent = getFileContent(errorFile);
    int offset = calculateOffset(fileContent, columnNumber, lineNumber);
    int length = calculateIssueLength(fileContent.get(lineNumber), partAtIndex(parts, 4));

    Severity severity = calculateSeverity(error.getSeverity());
    String message = error.getMessage();
    SolcIssue solcIssue = new SolcIssue();
    solcIssue.setIFile(errorFile);
    solcIssue.setLineNumber(lineNumber);
    solcIssue.setColumnNumber(columnNumber);
    solcIssue.setSeverity(severity);
    solcIssue.setMessage(message);
    solcIssue.setOffset(offset);
    solcIssue.setLength(length);
    solcIssue.setErrorCode(createErrorCodeFromMessage(severity, message));
    EObject element = getEObject(errorFile, offset);
    solcIssue.setUriToProblem(EcoreUtil.getURI(element));
    return solcIssue;
}
项目:eclipse-batch-editor    文件:BatchEditor.java   
private boolean isMarkerChangeForThisEditor(IResourceChangeEvent event) {
    IResource resource = ResourceUtil.getResource(getEditorInput());
    if (resource == null) {
        return false;
    }
    IPath path = resource.getFullPath();
    if (path == null) {
        return false;
    }
    IResourceDelta eventDelta = event.getDelta();
    if (eventDelta == null) {
        return false;
    }
    IResourceDelta delta = eventDelta.findMember(path);
    if (delta == null) {
        return false;
    }
    boolean isMarkerChangeForThisResource = (delta.getFlags() & IResourceDelta.MARKERS) != 0;
    return isMarkerChangeForThisResource;
}
项目:eclipse-jenkins-editor    文件:JenkinsEditorUtil.java   
public static void addLinterError(IEditorPart editor, JenkinsLinterError error) {
    if (editor == null) {
        return;
    }
    if (error == null) {
        return;
    }

    IEditorInput input = editor.getEditorInput();
    if (input == null) {
        return;
    }
    IResource editorResource = input.getAdapter(IResource.class);
    if (editorResource == null) {
        return;
    }
    try {
        linterMarkerHelper.createErrorMarker(editorResource, error.getMessage(), error.getLine());
    } catch (CoreException e) {
        logError("Was not able to add error markers", e);
    }

}
项目:pgcodekeeper    文件:ProjectEditorDiffer.java   
private IEditorInput createProjectScriptFile(String content, String filename) throws CoreException, IOException {
    Log.log(Log.LOG_INFO, "Creating file " + filename); //$NON-NLS-1$
    IProject iProject = proj.getProject();
    IFolder folder = iProject.getFolder(PROJ_PATH.MIGRATION_DIR);
    if (!folder.exists()){
        folder.create(IResource.NONE, true, null);
    }
    IFile file = folder.getFile(filename + ".sql"); //$NON-NLS-1$
    InputStream source = new ByteArrayInputStream(content.getBytes(proj.getProjectCharset()));
    file.create(source, IResource.NONE, null);
    return new FileEditorInput(iProject.getFile(file.getProjectRelativePath()));
}
项目:OCCI-Studio    文件:DesignerGeneratorAction.java   
private IProject generateDesignProject(String occieLocation, String designName, String designProjectName,
        final IProgressMonitor monitor) throws CoreException, IOException {

    // Load the ecore file.
    String ecoreLocation = occieLocation.replace(".occie", ".ecore");
    URI ecoreURI = URI.createFileURI(ecoreLocation);
    // Create a new resource set.
    ResourceSet resourceSet = new ResourceSetImpl();
    // Load the OCCI resource.
    org.eclipse.emf.ecore.resource.Resource resource = resourceSet.getResource(ecoreURI, true);
    // Return the first element.
    EPackage ePackage = (EPackage) resource.getContents().get(0);

    String extensionScheme = Occi2Ecore.convertEcoreNamespace2OcciScheme(ePackage.getNsURI());

    // Register the ePackage to avoid an error when trying to open the generated
    // .odesign file,
    EPackage.Registry.INSTANCE.put(ePackage.getNsURI(), ePackage);


    URI occieURI = URI.createFileURI(occieLocation);

    /*
     * Create design project
     */
    IProject project = DesignerGeneratorUtils.genDesignProject(designProjectName, designName, extensionScheme,
            new ProgressMonitorDialog(shell));

    /*
     * Create design model
     */
    org.eclipse.cmf.occi.core.gen.design.extended.main.Generate generator = new org.eclipse.cmf.occi.core.gen.design.extended.main.Generate(
            occieURI, project.getFolder("description").getLocation().toFile(), new ArrayList<String>());
    generator.doGenerate(BasicMonitor.toMonitor(monitor));
    project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    return project;
}
项目:java-debug    文件:JavaHotCodeReplaceProvider.java   
private void redefineTypesJDK(List<IResource> resources, List<String> qualifiedNames) throws DebugException {
    Map<ReferenceType, byte[]> typesToBytes = getTypesToBytes(resources, qualifiedNames);
    try {
        currentDebugSession.getVM().redefineClasses(typesToBytes);
    } catch (UnsupportedOperationException | NoClassDefFoundError | VerifyError | ClassFormatError
            | ClassCircularityError e) {
        publishEvent(HotCodeReplaceEvent.EventType.ERROR, e.getMessage());
        throw new DebugException("Failed to redefine classes: " + e.getMessage());
    }
}
项目:gw4e.project    文件:ResourceManagerTest.java   
@Test
public void testCreateFileDeleteIfExistsStringStringStringIProgressMonitor() throws Exception {
    IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true, true);
    IFile impl = (IFile) ResourceManager
            .getResource(project.getProject().getFullPath().append("src/test/java/SimpleImpl.java").toString());
    int[] count = new int[1];

    count[0] = 0;
    IResourceVisitor visitor = new IResourceVisitor() {
        @Override
        public boolean visit(IResource resource) throws CoreException {
            if (resource.getFileExtension() != null && resource.getFileExtension().equalsIgnoreCase("java")) {
                count[0] = count[0] + 1;
            }
            return true;
        }
    };
    impl.getParent().accept(visitor);
    assertTrue(count[0] == 1);

    ResourceManager.createFileDeleteIfExists(impl.getParent().getFullPath().toString(), "SimpleImpl.java", "",
            new NullProgressMonitor());
    String s = IOHelper.getContent(impl);
    assertTrue(s.length() == 0);

    count[0] = 0;
    impl.getParent().accept(visitor);
    assertTrue(count[0] == 2);
}
项目:n4js    文件:AbstractBuilderParticipantTest.java   
/***/
protected void replaceFileContentAndWaitForRefresh(IFolder folder, IFile file, String newContent)
        throws IOException, CoreException {
    File fileInFilesystem = file.getLocation().toFile();
    FileWriter fileWriter = new FileWriter(fileInFilesystem);
    fileWriter.write(newContent);
    fileWriter.close();
    folder.refreshLocal(IResource.DEPTH_INFINITE, monitor());
    waitForAutoBuild();
}
项目:pgcodekeeper    文件:SQLEditor.java   
@Override
public void doSave(IProgressMonitor progressMonitor) {
    super.doSave(progressMonitor);
    IResource res = ResourceUtil.getResource(getEditorInput());
    try {
        if (res == null || !PgUIDumpLoader.isInProject(res)) {
            refreshParser(getParser(), res, progressMonitor);
        }
    } catch (Exception ex) {
        Log.log(ex);
    }
}
项目:neoscada    文件:RecipeHelper.java   
public static void processFile ( final IResource file, final IProgressMonitor monitor ) throws Exception
{
    final ModelLoader<Definition> loader = new ModelLoader<Definition> ( Definition.class );

    final Definition def = loader.load ( file.getLocationURI () );

    processFile ( file.getParent (), def, null, monitor );
}
项目:Open_Source_ECOA_Toolset_AS5    文件:PluginUtil.java   
public ArrayList<String> getResourcesWithExtension(String ext, String containerName) {
    ArrayList<String> ret = new ArrayList<String>();
    if (containerName != null) {
        String[] names = StringUtils.split(containerName, "/");
        IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
        IResource resource = wsRoot.findMember(new Path("/" + names[0]));
        IPath loc = resource.getLocation();
        File prjLoc = new File(loc.toString());
        Collection<File> res = FileUtils.listFiles(prjLoc, FileFilterUtils.suffixFileFilter(ext, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE);
        for (File file : res)
            ret.add(file.getAbsolutePath());
    }
    return ret;
}
项目:vertigo-chroma-kspplugin    文件:ResourceStore.java   
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
    IResource resource = delta.getResource();

    /* Dossier target : on n'explore pas. */
    if (ResourceUtils.isTargetFolder(resource)) {
        return false;
    }

    /* Filtre sur les fichiers. */
    if (!(resource instanceof IFile)) {
        /* Dossier : on continue la visite. */
        return true;
    }

    /* La ressource est un fichier. */
    IFile file = (IFile) resource;

    /* Vérifie que le magasin est concerné par ce fichier. */
    boolean isCandidate = implementor.isCandidate(file);
    if (!isCandidate) {
        return false;
    }

    switch (delta.getKind()) {
    case IResourceDelta.REMOVED:
    case IResourceDelta.REMOVED_PHANTOM:
        /* Cas d'une suppression de fichier. */
        handleDeletion(file);
        break;
    default:
        /* Cas d'un ajout ou d'un changement : on traite le fichier. */
        handleChange(file);
        break;
    }

    /* Fin de la visite. */
    return false;
}
项目:eclipse-commons    文件:TestToIResourcePositive.java   
@Test
public void workspaceRoot() throws Exception {
    URI uri = URI.createPlatformResourceURI("", true);
    IResource iResource = UriUtils.toIResource(uri);

    assertTrue(iResource instanceof IWorkspaceRoot);
    assertTrue(iResource.exists());
    assertEquals("/", iResource.getFullPath().toString());
}
项目:n4js    文件:LaunchConfigurationMainTab.java   
/***
 * Open a resource chooser to select a file
 **/
protected void browseFiles() {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    ResourceListSelectionDialog dialog = new ResourceListSelectionDialog(getShell(), root, IResource.FILE);
    dialog.setTitle("Search File");
    if (dialog.open() == Window.OK) {
        Object[] files = dialog.getResult();
        IFile file = (IFile) files[0];
        fileText.setText(file.getFullPath().toString());
    }

}
项目:Tarski    文件:CreatingAtomWizardContentProvider.java   
@Override
public boolean hasChildren(Object element) {
  if (element instanceof IResource) {
    return true;
  } else {
    return false;
  }
}
项目:n4js    文件:ModuleSpecifierSelectionDialog.java   
@Override
protected void computeResult() {

    Object selection = treeViewer.getStructuredSelection().getFirstElement();

    if (selection == null) {
        return;
    }

    String moduleName = elementNameInput.getText();
    String moduleFileExtension = elementNameInput.getSuffix();

    // For selected files where the element name input equals the selected file
    if (selection instanceof IFile
            && ((IFile) selection).getFullPath().removeFileExtension().lastSegment().equals(moduleName)) {
        // Use the selected file's path as result
        IPath fileSpec = sourceFolderRelativePath((IResource) selection);
        this.setResult(Arrays.asList(fileSpec.toString()));
        return;
    } else if (selection instanceof IResource) {
        // For files with different element name input value, use their container as basepath
        if (selection instanceof IFile) {
            selection = ((IFile) selection).getParent();
        }

        IFile moduleFile = ((IContainer) selection).getFile(new Path(moduleName + moduleFileExtension));
        this.setResult(
                Arrays.asList(moduleFile.getFullPath().makeRelativeTo(sourceFolder.getFullPath()).toString()));

        return;
    } else {
        updateError("Invalid selection type.");
    }
}
项目:gemoc-studio-modeldebugging    文件:AbstractCreateNewGemocLanguageProject.java   
@Override
public boolean performFinish() {

    try {
        createdProject = _askProjectNamePage.getProjectHandle();
        final String languageName = _askLanguageNamePage.getLanguageName();

        IWorkspace workspace = ResourcesPlugin.getWorkspace(); 
        final IProjectDescription description = workspace.newProjectDescription(createdProject.getName());
        if (!_askProjectNamePage.getLocationPath().equals(workspace.getRoot().getLocation()))
            description.setLocation(_askProjectNamePage.getLocationPath());
        //description.setLocationURI(_askProjectNamePage.getLocationURI());

        IWorkspaceRunnable operation = new IWorkspaceRunnable() {
             public void run(IProgressMonitor monitor) throws CoreException {
                 createdProject.create(description, monitor);
                 createdProject.open(monitor);
                 initializeProject(createdProject, languageName);
                 createdProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
                 createdProject.touch(new NullProgressMonitor()); // [FT] One touch to force eclipse to serialize the project properties that will update accordingly the gemoc actions in the menu.
                 //createdProject.build(IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor());
             }
        };
        ResourcesPlugin.getWorkspace().run(operation, null);
    } catch (CoreException exception) {
        Activator.error(exception.getMessage(), exception);
        return false;
    }
    return true;
}