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;
}
use of org.eclipse.core.resources.IResourceRuleFactory in project evosuite by EvoSuite.
the class ExtendSuiteAction method addTestJob.
// @Override
// public void selectionChanged(IAction action, ISelection selection) {
// currentSelection.clear();
//
// if (selection instanceof IStructuredSelection) {
// IStructuredSelection sel = (IStructuredSelection) selection;
//
// for (Object o : sel.toList()) {
// if (o instanceof IJavaElement) {
// IJavaElement jEl = (IJavaElement) o;
// try {
// IResource jRes = jEl.getCorrespondingResource();
// if (jRes != null) {
// jRes.accept(new IResourceVisitor() {
// @Override
// public boolean visit(IResource resource)
// throws CoreException {
// if ("java".equals(resource.getFileExtension()))
// currentSelection.add(resource);
// return true;
// }
// });
// }
// } catch (JavaModelException e) {
// System.err.println("Error while traversing resources!" + e);
// } catch (CoreException e) {
// System.err.println("Error while traversing resources!" + e);
// }
// }
// }
// }
// }
//
// @Override
// public void run(IAction action) {
// if (currentSelection.isEmpty()) {
// MessageDialog.openError(shell, "Evosuite",
// "Unable to generate test cases for selection: Cannot find .java files.");
// } else if (currentSelection.size() > 1) {
// MessageDialog.openError(shell, "Evosuite",
// "Please only select one class at a time.");
// } else {
//
// for (IResource res : currentSelection) {
// IProject proj = res.getProject();
// fixJUnitClassPath(JavaCore.create(proj));
// generateTests(res);
// }
// }
// }
/**
* Add a new test generation job to the job queue
*
* @param target
*/
@Override
protected void addTestJob(final IResource target) {
IJavaElement element = JavaCore.create(target);
IJavaElement packageElement = element.getParent();
String packageName = packageElement.getElementName();
final String suiteClass = (!packageName.equals("") ? packageName + "." : "") + target.getName().replace(".java", "").replace(File.separator, ".");
System.out.println("Building new job for " + suiteClass);
DetermineSUT det = new DetermineSUT();
IJavaProject jProject = JavaCore.create(target.getProject());
try {
String classPath = target.getWorkspace().getRoot().findMember(jProject.getOutputLocation()).getLocation().toOSString();
String SUT = det.getSUTName(suiteClass, classPath);
// choose
SelectionDialog typeDialog = JavaUI.createTypeDialog(shell, new ProgressMonitorDialog(shell), target.getProject(), IJavaElementSearchConstants.CONSIDER_CLASSES, false);
Object[] sutDefault = new Object[1];
sutDefault[0] = SUT;
typeDialog.setInitialSelections(sutDefault);
typeDialog.setTitle("Please select the class under test");
typeDialog.open();
// Type selected by the user
Object[] result = typeDialog.getResult();
if (result.length > 0) {
SourceType sourceType = (SourceType) result[0];
SUT = sourceType.getFullyQualifiedName();
} else {
return;
}
Job job = new TestExtensionJob(shell, target, SUT, suiteClass);
job.setPriority(Job.SHORT);
IResourceRuleFactory ruleFactory = ResourcesPlugin.getWorkspace().getRuleFactory();
ISchedulingRule rule = ruleFactory.createRule(target.getProject());
// IFolder folder = proj.getFolder(ResourceUtil.EVOSUITE_FILES);
job.setRule(rule);
job.setUser(true);
// start as soon as possible
job.schedule();
} catch (JavaModelException e) {
e.printStackTrace();
} catch (NoJUnitClassException e) {
MessageDialog.openError(shell, "Evosuite", "Cannot find JUnit tests in " + suiteClass);
}
}
use of org.eclipse.core.resources.IResourceRuleFactory in project evosuite by EvoSuite.
the class TestGenerationAction method addTestJob.
/**
* Add a new test generation job to the job queue
*
* @param target
*/
protected void addTestJob(final IResource target) {
IJavaElement element = JavaCore.create(target);
if (element == null) {
return;
}
IJavaElement packageElement = element.getParent();
String packageName = packageElement.getElementName();
final String targetClass = (!packageName.isEmpty() ? packageName + "." : "") + target.getName().replace(".java", "").replace(File.separator, ".");
System.out.println("* Scheduling new automated job for " + targetClass);
final String targetClassWithoutPackage = target.getName().replace(".java", "");
final String suiteClassName = targetClass + Properties.JUNIT_SUFFIX;
final String suiteFileName = target.getProject().getLocation() + "/evosuite-tests/" + suiteClassName.replace('.', File.separatorChar) + ".java";
System.out.println("Checking for " + suiteFileName);
File suiteFile = new File(suiteFileName);
Job job = null;
if (suiteFile.exists()) {
MessageDialog dialog = new MessageDialog(shell, "Existing test suite found", // image
null, "A test suite for class \"" + targetClass + "\" already exists. EvoSuite will overwrite this test suite. Do you really want to proceed?", MessageDialog.QUESTION_WITH_CANCEL, new String[] { "Overwrite", "Extend", "Rename Original", "Cancel" }, 0);
int returnCode = dialog.open();
// 1 == extend
if (returnCode == 1) {
IWorkspaceRoot wroot = target.getWorkspace().getRoot();
IResource suiteResource = wroot.getFileForLocation(new Path(suiteFileName));
job = new TestExtensionJob(shell, suiteResource, targetClass, suiteClassName);
} else if (returnCode == 2) {
// 2 == Rename
renameSuite(target, packageName, targetClassWithoutPackage + Properties.JUNIT_SUFFIX + ".java");
} else if (returnCode > 2) {
// Cancel
return;
}
}
if (job == null)
job = new TestGenerationJob(shell, target, targetClass, suiteClassName);
job.setPriority(Job.SHORT);
IResourceRuleFactory ruleFactory = ResourcesPlugin.getWorkspace().getRuleFactory();
ISchedulingRule rule = ruleFactory.createRule(target.getProject());
// IFolder folder = proj.getFolder(ResourceUtil.EVOSUITE_FILES);
job.setRule(rule);
job.setUser(true);
// start as soon as possible
job.schedule();
}
use of org.eclipse.core.resources.IResourceRuleFactory in project titan.EclipsePlug-ins by eclipse.
the class FormatLog method createRuleFromResources.
private ISchedulingRule createRuleFromResources(final IFile file, final IFile[] targetFiles) {
final IResourceRuleFactory ruleFactory = ResourcesPlugin.getWorkspace().getRuleFactory();
final ISchedulingRule rule1 = ruleFactory.createRule(file);
ISchedulingRule combinedRule = MultiRule.combine(rule1, null);
for (final IFile targetFile : targetFiles) {
combinedRule = MultiRule.combine(ruleFactory.createRule(targetFile), combinedRule);
}
return combinedRule;
}
use of org.eclipse.core.resources.IResourceRuleFactory in project titan.EclipsePlug-ins by eclipse.
the class ChecklistGenerator method run.
public void run(final ISelection selection) {
ArrayList<IFile> files = new ArrayList<IFile>();
if (selection instanceof IStructuredSelection) {
IStructuredSelection structSelection = (IStructuredSelection) selection;
files = new ArrayList<IFile>(structSelection.size());
for (Object selected : structSelection.toList()) {
if (selected instanceof IFile) {
IFile file = (IFile) selected;
if (file.isAccessible()) {
files.add(file);
}
}
}
}
// 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>(" + errorMessages.size() + ");\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_constructor(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_constructor(\"" + 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(\"Semantic_Analizer_Tests\");");
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();
}
}
Aggregations