Search in sources :

Example 6 with IResourceRuleFactory

use of org.eclipse.core.resources.IResourceRuleFactory in project titan.EclipsePlug-ins by eclipse.

the class ChecklistGenerator method run.

@Override
public void run(final IAction action) {
    // for every selected file
    for (int i = 0, size = files.size(); i < size; i++) {
        final IFile file = files.get(i);
        IPath path = file.getLocation();
        final File source = path.toFile();
        String extension = path.getFileExtension();
        path = path.removeFileExtension();
        IPath targetPath = path.addFileExtension(extension + "_processed");
        int matching = targetPath.matchingFirstSegments(file.getProject().getLocation());
        final IFile target = file.getProject().getFile(targetPath.removeFirstSegments(matching));
        // process the files (possibly  in parallel) in a workspace job so that the user can do something else.
        WorkspaceJob saveJob = new WorkspaceJob("Generating checklist from file" + file.getName()) {

            @Override
            public IStatus runInWorkspace(final IProgressMonitor monitor) {
                long formattingStart = System.currentTimeMillis();
                IProgressMonitor internalMonitor = monitor == null ? new NullProgressMonitor() : monitor;
                internalMonitor.beginTask("Processing " + file.getName(), IProgressMonitor.UNKNOWN);
                ArrayList<Error_Message> errorMessages = new ArrayList<Error_Message>();
                // read in the error message from the file
                BufferedReader bufferedInput = null;
                try {
                    FileInputStream input = new FileInputStream(source);
                    bufferedInput = new BufferedReader(new InputStreamReader(input));
                    // process the first line to see where the needed columns are
                    // the used might have reordered them
                    String line;
                    Pattern p = Pattern.compile("\t");
                    String[] items;
                    int descriptionIndex = -1;
                    int fileNameIndex = -1;
                    int pathIndex = -1;
                    int locationIndex = -1;
                    line = bufferedInput.readLine();
                    if (line != null) {
                        items = p.split(line);
                        for (int i = 0; i < items.length; i++) {
                            if ("Description".equals(items[i])) {
                                descriptionIndex = i;
                            } else if ("Resource".equals(items[i])) {
                                fileNameIndex = i;
                            } else if ("Path".equals(items[i])) {
                                pathIndex = i;
                            } else if ("Location".equals(items[i])) {
                                locationIndex = i;
                            }
                        }
                    }
                    if (descriptionIndex == -1 || fileNameIndex == -1 || pathIndex == -1 || locationIndex == -1) {
                        // FATAL error
                        return new Status(IStatus.ERROR, ProductConstants.PRODUCT_ID_DESIGNER, IStatus.OK, "The input must have at least the Description, Resource, Path and Location columns", null);
                    }
                    // process the rest of the file.
                    Matcher locationFormatMatcher = LOCATION_FORMAT_PATTERN.matcher("");
                    String rawLocation;
                    line = bufferedInput.readLine();
                    while (line != null) {
                        items = p.split(line);
                        rawLocation = items[locationIndex];
                        if (locationFormatMatcher.reset(rawLocation).matches()) {
                            String text = items[descriptionIndex];
                            StringBuilder builder = new StringBuilder(text);
                            builder = handleEscapeSequences(builder);
                            errorMessages.add(new Error_Message(builder.toString(), new Integer(locationFormatMatcher.group(1)).intValue(), items[fileNameIndex], items[pathIndex]));
                        }
                        line = bufferedInput.readLine();
                    }
                    bufferedInput.close();
                } catch (FileNotFoundException e) {
                    ErrorReporter.logExceptionStackTrace(e);
                } catch (IOException e) {
                    ErrorReporter.logExceptionStackTrace(e);
                    errorMessages.clear();
                } finally {
                    if (bufferedInput != null) {
                        try {
                            bufferedInput.close();
                        } catch (IOException e) {
                            ErrorReporter.logExceptionStackTrace(e);
                        }
                    }
                }
                if (errorMessages.size() == 0) {
                    return new Status(IStatus.ERROR, ProductConstants.PRODUCT_ID_DESIGNER, IStatus.OK, "No error messages found in the file", null);
                }
                errorMessages.trimToSize();
                // sort the error messages
                Collections.sort(errorMessages, new Comparator<Error_Message>() {

                    @Override
                    public int compare(final Error_Message o1, final Error_Message o2) {
                        int order = o1.filename.compareTo(o2.filename);
                        if (order != 0) {
                            return order;
                        }
                        return o1.line - o2.line;
                    }
                });
                StringBuilder codeSectionBuilder = new StringBuilder();
                int inside_row = 1;
                int followings = 0;
                Error_Message sectionStarterError = errorMessages.get(0);
                Error_Message actualError;
                ArrayList<TestSuiteElement> testSuiteElements = new ArrayList<TestSuiteElement>();
                int last_row = sectionStarterError.line;
                testSuiteElements.add(new TestSuiteElement(sectionStarterError.filename, sectionStarterError.location.substring(sectionStarterError.location.indexOf('/', 1) + 1)));
                codeSectionBuilder.append("\tprivate ArrayList<MarkerToCheck> " + sectionStarterError.filename.replace('.', '_') + "_initializer() {\n");
                codeSectionBuilder.append("\t\t//" + sectionStarterError.filename + "\n");
                codeSectionBuilder.append("\t\tArrayList<MarkerToCheck> markersToCheck = new ArrayList<MarkerToCheck>();\n");
                codeSectionBuilder.append("\t\tint lineNum = " + sectionStarterError.line + ";\n");
                AtomicInteger printI = new AtomicInteger(1);
                // process the error message one-by-one, detecting error sections, and build their representation in a StringBuilder.
                for (int i = 1, size = errorMessages.size(); i < size; i++) {
                    actualError = errorMessages.get(i);
                    if (sectionStarterError.filename.equals(actualError.filename) && sectionStarterError.text.equals(actualError.text)) {
                        if (sectionStarterError.line == actualError.line) {
                            inside_row++;
                            continue;
                        } else if (sectionStarterError.line + followings + 1 == actualError.line && inside_row == 1) {
                            followings++;
                            continue;
                        }
                    }
                    printErrorSection(codeSectionBuilder, sectionStarterError, inside_row, followings, last_row, printI);
                    last_row = sectionStarterError.line;
                    if (followings > 0) {
                        last_row += followings + 1;
                    }
                    if (!sectionStarterError.filename.equals(actualError.filename)) {
                        last_row = actualError.line;
                        testSuiteElements.add(new TestSuiteElement(actualError.filename, actualError.location.substring(actualError.location.indexOf('/', 1) + 1)));
                        codeSectionBuilder.append("\n");
                        codeSectionBuilder.append("\t\treturn markersToCheck;\n");
                        codeSectionBuilder.append("\t}\n\n");
                        codeSectionBuilder.append("\t private ArrayList<MarkerToCheck> " + actualError.filename.replace('.', '_') + "_initializer() {\n");
                        codeSectionBuilder.append("\t\t//" + actualError.filename + "\n");
                        codeSectionBuilder.append("\t\tArrayList<MarkerToCheck> markersToCheck = new ArrayList<MarkerToCheck>();\n");
                        codeSectionBuilder.append("\t\tint lineNum = " + actualError.line + ";\n");
                        printI.set(1);
                    }
                    sectionStarterError = actualError;
                    inside_row = 1;
                    followings = 0;
                }
                printErrorSection(codeSectionBuilder, sectionStarterError, inside_row, followings, last_row, printI);
                codeSectionBuilder.append("\n");
                codeSectionBuilder.append("\t\treturn markersToCheck;\n");
                codeSectionBuilder.append("\t}\n\n");
                // create a write that will write the output to a file
                BufferedWriter bufferedwriter = null;
                try {
                    bufferedwriter = new BufferedWriter(new FileWriter(target.getLocation().toFile()));
                } catch (IOException e) {
                    ErrorReporter.logExceptionStackTrace(e);
                    return new Status(IStatus.ERROR, ProductConstants.PRODUCT_ID_DESIGNER, IStatus.OK, e.getMessage() != null ? e.getMessage() : "", e);
                }
                PrintWriter printWriter = new PrintWriter(bufferedwriter);
                TestSuiteElement element;
                for (int i = 0; i < testSuiteElements.size(); i++) {
                    element = testSuiteElements.get(i);
                    printWriter.println("\t//" + element.fileName.replace('.', '_'));
                }
                printWriter.println("\t");
                // printWriter.println("\tstatic {");
                /*					for (int i = 0; i < testSuiteElements.size(); i++) {
						element = testSuiteElements.get(i);
						
						printWriter.println("\t\t" + element.fileName.replace('.', '_') + "_initializer(); //" + element.fileName.replace('.', '_'));
					}*/
                /*					
					printWriter.println("\t\tint i = 0;");
					printWriter.println("\t\tint lineNum = 0;");
					printWriter.println("");
*/
                // printWriter.println("\t}\n\n");
                printWriter.print(codeSectionBuilder);
                printWriter.println("");
                printWriter.println("\t/*");
                printWriter.println("\t* Auto-generated method stub");
                printWriter.println("\t* @param name The name of the test package");
                printWriter.println("\t*/");
                printWriter.println("\tpublic FILL_ME_OUT_contsructor(final String name) {");
                printWriter.println("\t\tsuper(name);");
                printWriter.println("\t}");
                printWriter.println("");
                // test suite code
                printWriter.println("\t/*");
                printWriter.println("\t* Auto-generated method stub");
                printWriter.println("\t*/");
                printWriter.println("\tpublic static Test suite() {");
                printWriter.println("\t\tTestSuite suite = new TestSuite(\"FILL_ME_OUT tests\"); //FIXME correct");
                printWriter.println("");
                for (int i = 0; i < testSuiteElements.size(); i++) {
                    element = testSuiteElements.get(i);
                    printWriter.println("\t\tsuite.addTest(new FILL_ME_OUT_contsructor(\"" + element.fileName.replace('.', '_') + "\"));");
                }
                printWriter.println("");
                printWriter.println("\t\tTestSetup wrapper = new TestSetup(suite) {");
                printWriter.println("");
                printWriter.println("\t\t\t@Override");
                printWriter.println("\t\t\tprotected void setUp() throws Exception {");
                printWriter.println("\t\t\t}");
                printWriter.println("");
                printWriter.println("\t\t};");
                printWriter.println("");
                printWriter.println("\treturn wrapper;");
                printWriter.println("\t}");
                for (int i = 0; i < testSuiteElements.size(); i++) {
                    element = testSuiteElements.get(i);
                    printWriter.println("");
                    printWriter.println("\t// Auto-generated method stub");
                    printWriter.println("\tpublic void " + element.fileName.replace('.', '_') + "() throws Exception {");
                    printWriter.println("\t\tArrayList<MarkerToCheck> markersToCheck = " + element.fileName.replace('.', '_') + "_initializer();");
                    printWriter.println("\t\tIProject project = WorkspaceHandlingLibrary.getWorkspace().getRoot().getProject(\"Regression_test_project\");");
                    printWriter.println("");
                    printWriter.println("\t\tArrayList<Map<?, ?>> fileMarkerlist = Designer_plugin_tests.semanticMarkers.get(project.getFile(\"" + element.fileLocation + "/" + element.fileName + "\"));");
                    printWriter.println("");
                    printWriter.println("\t\tassertNotNull(fileMarkerlist);");
                    printWriter.println("");
                    printWriter.println("\t\tfor (int i = markersToCheck.size() - 1; i >= 0; i--) {");
                    printWriter.println("\t\t\tMarkerHandlingLibrary.searchNDestroyFittingMarker(fileMarkerlist, markersToCheck.get(i).getMarkerMap(), true);");
                    printWriter.println("\t\t}");
                    printWriter.println("");
                    printWriter.println("\t\tmarkersToCheck.clear();");
                    printWriter.println("\t}");
                }
                printWriter.close();
                try {
                    target.refreshLocal(IResource.DEPTH_ZERO, null);
                } catch (CoreException e) {
                    ErrorReporter.logExceptionStackTrace(e);
                }
                TITANDebugConsole.println("Processing took " + (System.currentTimeMillis() - formattingStart) / 1000.0 + " secs");
                internalMonitor.done();
                return Status.OK_STATUS;
            }
        };
        IResourceRuleFactory ruleFactory = ResourcesPlugin.getWorkspace().getRuleFactory();
        ISchedulingRule rule1 = ruleFactory.createRule(file);
        ISchedulingRule rule2 = ruleFactory.createRule(target);
        ISchedulingRule combinedRule = MultiRule.combine(rule1, null);
        combinedRule = MultiRule.combine(rule2, combinedRule);
        saveJob.setRule(combinedRule);
        saveJob.setPriority(Job.LONG);
        saveJob.setUser(true);
        saveJob.setProperty(IProgressConstants.ICON_PROPERTY, ImageCache.getImageDescriptor("titan.gif"));
        saveJob.schedule();
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IFile(org.eclipse.core.resources.IFile) Matcher(java.util.regex.Matcher) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) BufferedWriter(java.io.BufferedWriter) PrintWriter(java.io.PrintWriter) IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) Pattern(java.util.regex.Pattern) IPath(org.eclipse.core.runtime.IPath) InputStreamReader(java.io.InputStreamReader) WorkspaceJob(org.eclipse.core.resources.WorkspaceJob) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) ISchedulingRule(org.eclipse.core.runtime.jobs.ISchedulingRule) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BufferedReader(java.io.BufferedReader) IResourceRuleFactory(org.eclipse.core.resources.IResourceRuleFactory) IFile(org.eclipse.core.resources.IFile) File(java.io.File)

Example 7 with IResourceRuleFactory

use of org.eclipse.core.resources.IResourceRuleFactory in project pmd-eclipse-plugin by pmd.

the class ReviewCodeCmd method getSchedulingRule.

/**
 * @return the scheduling rule needed to apply markers
 */
private ISchedulingRule getSchedulingRule() {
    final IWorkspace workspace = ResourcesPlugin.getWorkspace();
    final IResourceRuleFactory ruleFactory = workspace.getRuleFactory();
    ISchedulingRule rule;
    if (resources.isEmpty()) {
        rule = ruleFactory.markerRule(resourceDelta.getResource().getProject());
    } else {
        ISchedulingRule[] rules = new ISchedulingRule[resources.size()];
        for (int i = 0; i < rules.length; i++) {
            rules[i] = ruleFactory.markerRule((IResource) resources.get(i));
        }
        rule = new MultiRule(resources.toArray(rules));
    }
    return rule;
}
Also used : MultiRule(org.eclipse.core.runtime.jobs.MultiRule) IWorkspace(org.eclipse.core.resources.IWorkspace) IResourceRuleFactory(org.eclipse.core.resources.IResourceRuleFactory) IResource(org.eclipse.core.resources.IResource) ISchedulingRule(org.eclipse.core.runtime.jobs.ISchedulingRule)

Example 8 with IResourceRuleFactory

use of org.eclipse.core.resources.IResourceRuleFactory in project che by eclipse.

the class Rules method factoryFor.

/**
	 * Returns the scheduling rule factory for the given resource
	 */
private IResourceRuleFactory factoryFor(IResource destination) {
    IResourceRuleFactory fac = projectsToRules.get(destination.getFullPath().segment(0));
    if (fac == null) {
        //use the default factory if the project is not yet accessible
        if (!destination.getProject().isAccessible())
            return defaultFactory;
        //ask the team hook to supply one
        fac = teamHook.getRuleFactory(destination.getProject());
        projectsToRules.put(destination.getFullPath().segment(0), fac);
    }
    return fac;
}
Also used : IResourceRuleFactory(org.eclipse.core.resources.IResourceRuleFactory)

Example 9 with IResourceRuleFactory

use of org.eclipse.core.resources.IResourceRuleFactory in project eclipse.platform.text by eclipse.

the class ResourceTextFileBufferManager method computeValidateStateRule.

private ISchedulingRule computeValidateStateRule(IFileBuffer[] fileBuffers) {
    ArrayList<IResource> list = new ArrayList<>();
    for (IFileBuffer fileBuffer : fileBuffers) {
        IResource resource = getWorkspaceFile(fileBuffer);
        if (resource != null)
            list.add(resource);
    }
    IResource[] resources = new IResource[list.size()];
    list.toArray(resources);
    IResourceRuleFactory factory = ResourcesPlugin.getWorkspace().getRuleFactory();
    return factory.validateEditRule(resources);
}
Also used : IFileBuffer(org.eclipse.core.filebuffers.IFileBuffer) ArrayList(java.util.ArrayList) IResourceRuleFactory(org.eclipse.core.resources.IResourceRuleFactory) IResource(org.eclipse.core.resources.IResource)

Example 10 with IResourceRuleFactory

use of org.eclipse.core.resources.IResourceRuleFactory in project webtools.servertools by eclipse.

the class DeleteServerDialog method buttonPressed.

protected void buttonPressed(int buttonId) {
    if (buttonId == OK) {
        final boolean checked = (checkDeleteConfigs != null && checkDeleteConfigs.getSelection());
        final boolean deleteRunning = (checkDeleteRunning == null || checkDeleteRunning.getSelection());
        final boolean deleteRunningStop = (checkDeleteRunningStop != null && checkDeleteRunningStop.getSelection());
        Thread t = new Thread("Delete servers") {

            public void run() {
                if (runningServersList.size() > 0) {
                    // stop servers and/or updates servers' list
                    prepareForDeletion(deleteRunning, deleteRunningStop);
                }
                Job job = new Job(Messages.deleteServerTask) {

                    protected IStatus run(IProgressMonitor monitor) {
                        if (servers.length == 0) {
                            // all servers have been deleted from list
                            return Status.OK_STATUS;
                        }
                        try {
                            if (monitor.isCanceled())
                                return Status.CANCEL_STATUS;
                            for (DeleteServerDialogExtension curDialogExtension : dialogExtensionLst) {
                                curDialogExtension.performPreDeleteAction(monitor);
                            }
                            int size = servers.length;
                            for (int i = 0; i < size; i++) servers[i].delete();
                            if (monitor.isCanceled())
                                return Status.CANCEL_STATUS;
                            if (checked) {
                                size = configs.length;
                                for (int i = 0; i < size; i++) {
                                    configs[i].refreshLocal(IResource.DEPTH_INFINITE, monitor);
                                    configs[i].delete(true, true, monitor);
                                }
                            }
                            for (DeleteServerDialogExtension curDialogExtension : dialogExtensionLst) {
                                curDialogExtension.performPostDeleteAction(monitor);
                            }
                        } catch (Exception e) {
                            if (Trace.SEVERE) {
                                Trace.trace(Trace.STRING_SEVERE, "Error while deleting resources", e);
                            }
                            return new Status(IStatus.ERROR, ServerUIPlugin.PLUGIN_ID, 0, e.getMessage(), e);
                        }
                        return Status.OK_STATUS;
                    }
                };
                // set rule for workspace and servers
                int size = servers.length;
                ISchedulingRule[] rules = new ISchedulingRule[size + 1];
                for (int i = 0; i < size; i++) rules[i] = servers[i];
                IResourceRuleFactory ruleFactory = ResourcesPlugin.getWorkspace().getRuleFactory();
                rules[size] = ruleFactory.createRule(ResourcesPlugin.getWorkspace().getRoot());
                job.setRule(MultiRule.combine(rules));
                job.setPriority(Job.BUILD);
                job.schedule();
            }
        };
        t.setDaemon(true);
        t.start();
    }
    super.buttonPressed(buttonId);
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) IResourceRuleFactory(org.eclipse.core.resources.IResourceRuleFactory) Job(org.eclipse.core.runtime.jobs.Job) DeleteServerDialogExtension(org.eclipse.wst.server.ui.DeleteServerDialogExtension) ISchedulingRule(org.eclipse.core.runtime.jobs.ISchedulingRule)

Aggregations

IResourceRuleFactory (org.eclipse.core.resources.IResourceRuleFactory)17 ISchedulingRule (org.eclipse.core.runtime.jobs.ISchedulingRule)13 ArrayList (java.util.ArrayList)5 IFile (org.eclipse.core.resources.IFile)5 IResource (org.eclipse.core.resources.IResource)5 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)5 IPath (org.eclipse.core.runtime.IPath)4 File (java.io.File)3 WorkspaceJob (org.eclipse.core.resources.WorkspaceJob)3 CoreException (org.eclipse.core.runtime.CoreException)3 IStatus (org.eclipse.core.runtime.IStatus)3 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)3 Status (org.eclipse.core.runtime.Status)3 Job (org.eclipse.core.runtime.jobs.Job)3 BufferedReader (java.io.BufferedReader)2 BufferedWriter (java.io.BufferedWriter)2 FileInputStream (java.io.FileInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 FileWriter (java.io.FileWriter)2 IOException (java.io.IOException)2