/** * Determine if the supplied IFile has any outstanding problem markers. If markers are found, * dialogs are displayed. * * @param mxdFile the file containing the extension definition * @return <code>true</code> if problems were found */ private static boolean checkProblemMarkers(IFile mxdFile) { IMarker[] markers = null; boolean errorOccurred = false; try { markers = mxdFile.findMarkers( UiConstants.ExtensionIds.PROBLEM_MARKER, false, IResource.DEPTH_INFINITE); } catch (CoreException ex) { Util.log(ex); errorOccurred = true; } // Notify user if error getting markers if (errorOccurred) { MessageDialog.openError( getShell(), Messages.checkMedProblemMarkersErrorTitle, Messages.checkMedProblemMarkersErrorMsg); return true; } if (markers.length > 0) { MessageDialog.openError( getShell(), Messages.checkMedProblemMarkersHasErrorsTitle, Messages.checkMedProblemMarkersHasErrorsMsg); return true; } return false; }
private IMarker findBreakpointMarker(IFile srcFile, int lineNumber) throws CoreException { IMarker[] markers = srcFile.findMarkers(IBreakpoint.LINE_BREAKPOINT_MARKER, true, IResource.DEPTH_INFINITE); for (int k = 0; k < markers.length; k++) { if (((Integer) markers[k].getAttribute(IMarker.LINE_NUMBER)).intValue() == lineNumber) { return markers[k]; } } return null; }
public void checkEntityProgram(final String contents, final int expectedErrors) { try { String _plus = (this.TEST_PROJECT + "/src/test.entities"); final IFile file = IResourcesSetupUtil.createFile(_plus, contents); IResourcesSetupUtil.waitForAutoBuild(); IMarker[] _findMarkers = file.findMarkers(EValidator.MARKER, true, IResource.DEPTH_INFINITE); int _size = ((List<IMarker>) Conversions.doWrapArray(_findMarkers)).size(); Assert.assertEquals(expectedErrors, _size); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
private void assertNoErrors(final IFile file) { try { final IMarker[] findMarkers = file.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE); for (final IMarker iMarker : findMarkers) { String _message = MarkerUtilities.getMessage(iMarker); int _severity = MarkerUtilities.getSeverity(iMarker); boolean _equals = (_severity == IMarker.SEVERITY_ERROR); Assert.assertFalse(_message, _equals); } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
/** * Checks if the file already the given marker. * * @param message * @param line * @param file * @return */ private boolean hasSameMarker(String message, int line, IFile file) { try { IMarker[] markers = file.findMarkers(null, true, IResource.DEPTH_INFINITE); for (IMarker m : markers) { if (m.getAttribute(IMarker.LINE_NUMBER, -1) == line) { if (m.getAttribute(IMarker.MESSAGE, "xxx").equals(message)) { return true; } } } } catch (CoreException e) { } return false; }
/** * Tests wiring validation. * * @throws Exception if a failure occurs. */ public void testWiringValidation() throws Exception { IProject project = importProject("test-data/validator-tests/wiring-validation-tests/pom.xml"); waitForJobsToComplete(); project.build(IncrementalProjectBuilder.FULL_BUILD, monitor); waitForJobsToComplete(); project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor); waitForJobsToComplete(); IFile switchYardFile = project.getFile("src/main/resources/META-INF/switchyard.xml"); assertTrue("switchyard.xml does not exist.", switchYardFile != null && switchYardFile.exists()); IMarker[] markers = switchYardFile.findMarkers( SwitchYardProjectValidator.SWITCHYARD_MARKER_ID, true, IFile.DEPTH_ZERO); int errorCount = 0; int warningCount = 0; int infoCount = 0; int unknownCount = 0; for (IMarker marker : markers) { switch (marker.getAttribute(IMarker.SEVERITY, -1)) { case IMarker.SEVERITY_ERROR: ++errorCount; break; case IMarker.SEVERITY_INFO: ++infoCount; break; case IMarker.SEVERITY_WARNING: ++warningCount; break; default: ++unknownCount; break; } } assertEquals("Expecting 14 errors: " + WorkspaceHelpers.toString(markers), 14, errorCount); assertEquals("Expecting 4 warnings: " + WorkspaceHelpers.toString(markers), 4, warningCount); assertEquals("Expecting 0 infos: " + WorkspaceHelpers.toString(markers), 0, infoCount); assertEquals( "Unexpected marker severity (not info, warning, error): " + WorkspaceHelpers.toString(markers), 0, unknownCount); }
/** @throws PartInitException */ @Test public void testDS3894DomainAttributeWarning() throws Exception { IFile fragment = getProject().getFile(FRAGMENT); Assert.assertTrue(fragment.exists()); Object adapter = fragment.getAdapter(IOfsElement.class); if (adapter instanceof IOfsModelResource) { IOfsModelResource modelResource = (IOfsModelResource) adapter; Assert.assertFalse(ValidationUtil.validate(modelResource, null, true).isOK()); IMarker[] markers = fragment.findMarkers(ValidationMarkerUtil.MARKER_ID, false, IResource.DEPTH_ONE); Assert.assertTrue(markers.length == 1); IMarker marker = markers[0]; Assert.assertTrue(marker.getAttribute(IMarker.SEVERITY).equals(IMarker.SEVERITY_WARNING)); String msg = "The domain attribute is not defined"; Assert.assertTrue(marker.getAttribute(IMarker.MESSAGE).equals(msg)); } else { Assert.fail("Cannot find test model!"); } }
void doHandleErrorsJob(Task[] errors, IFile file) { synchronized (this) // prevent simultaneous error updates on the same file { if (ResourcesPlugin.getWorkspace().isTreeLocked()) { IdeLog.logWarning( PHPEditorPlugin.getDefault(), "Error updating the document errors. The workspace tree is locked.", PHPEditorPlugin.DEBUG_SCOPE); // $NON-NLS-1$ } if (file == null || !file.exists()) { return; } int depth = IResource.DEPTH_INFINITE; try { IMarker[] problemMarkers = file.findMarkers(IMarker.TASK, true, depth); for (IMarker m : problemMarkers) { Object attribute2 = m.getAttribute(APTANA_TASK); if (attribute2 != null && attribute2.equals("true")) // $NON-NLS-1$ { m.delete(); } } for (Task t : errors) { IMarker problemMarker = file.createMarker(IMarker.TASK); problemMarker.setAttribute(IMarker.PRIORITY, t.getPriority()); problemMarker.setAttribute(IMarker.CHAR_START, t.getStart()); problemMarker.setAttribute(IMarker.CHAR_END, t.getEnd()); problemMarker.setAttribute(APTANA_TASK, Boolean.TRUE.toString()); problemMarker.setAttribute(IMarker.MESSAGE, t.getDescription()); problemMarker.setAttribute(IMarker.LINE_NUMBER, t.getLineNumber()); } } catch (Exception e) { IdeLog.logWarning( PHPEditorPlugin.getDefault(), "Error updating the PHP task-tags.", e, PHPEditorPlugin.DEBUG_SCOPE); // $NON-NLS-1$ } } }
private void findAndDeleteUnusedImports( PySelection ps, PyEdit edit, IDocumentExtension4 doc, IFile f) throws Exception { Iterator<MarkerAnnotationAndPosition> it; if (edit != null) { it = edit.getPySourceViewer().getMarkerIterator(); } else { IMarker markers[] = f.findMarkers(IMiscConstants.PYDEV_ANALYSIS_PROBLEM_MARKER, true, IResource.DEPTH_ZERO); MarkerAnnotationAndPosition maap[] = new MarkerAnnotationAndPosition[markers.length]; int ix = 0; for (IMarker m : markers) { int start = (Integer) m.getAttribute(IMarker.CHAR_START); int end = (Integer) m.getAttribute(IMarker.CHAR_END); maap[ix++] = new MarkerAnnotationAndPosition( new MarkerAnnotation(m), new Position(start, end - start)); } it = Arrays.asList(maap).iterator(); } ArrayList<MarkerAnnotationAndPosition> unusedImportsMarkers = getUnusedImports(it); sortInReverseDocumentOrder(unusedImportsMarkers); deleteImports(doc, ps, unusedImportsMarkers); }
/** * Processes the markers of the specified {@link IFile} and updates the error status of {@link * UiElementNode}s and {@link UiAttributeNode}s. * * @param inputFile the file being edited. */ private void updateFromExistingMarkers(IFile inputFile) { try { // get the markers for the file IMarker[] markers = inputFile.findMarkers(AdtConstants.MARKER_ANDROID, true, IResource.DEPTH_ZERO); AndroidManifestDescriptors desc = getManifestDescriptors(); if (desc != null) { ElementDescriptor appElement = desc.getApplicationElement(); if (appElement != null && mUiManifestNode != null) { UiElementNode appUiNode = mUiManifestNode.findUiChildNode(appElement.getXmlName()); List<UiElementNode> children = appUiNode.getUiChildren(); for (IMarker marker : markers) { processMarker(marker, children, IResourceDelta.ADDED); } } } } catch (CoreException e) { // findMarkers can throw an exception, in which case, we'll do nothing. } }
/** * Removes the not composed markers form the given source file and calls <code> * propagateMarkers(marker, file)</code> * * @param file */ protected void propagateMarkers(IFile file) { if (!file.exists()) { return; } try { IMarker[] markers = file.findMarkers(null, true, IResource.DEPTH_INFINITE); if (markers.length != 0) { LinkedList<IMarker> marker = new LinkedList<IMarker>(); for (IMarker m : markers) { String message = m.getAttribute(IMarker.MESSAGE, null); if (message == null || deleteMarker(message)) { m.delete(); } else if (propagateMarker(m)) { marker.add(m); } } if (!marker.isEmpty()) { propagateMarkers(marker, file); } } } catch (CoreException e) { FeatureHouseCorePlugin.getDefault().logError(e); } }
void performValidation(IFile f, IReporter reporter, IStructuredModel model, boolean inBatch) { if (model instanceof IDOMModel) { IDOMModel domModel = (IDOMModel) model; JsTranslationAdapterFactory.setupAdapterFactory(domModel); IDOMDocument xmlDoc = domModel.getDocument(); JsTranslationAdapter translationAdapter = (JsTranslationAdapter) xmlDoc.getAdapterFor(IJsTranslation.class); // translationAdapter.resourceChanged(); IJsTranslation translation = translationAdapter.getJsTranslation(false); if (!reporter.isCancelled()) { translation.setProblemCollectingActive(true); translation.reconcileCompilationUnit(); List problems = translation.getProblems(); // only update task markers if the model is the same as what's on disk boolean updateTasks = !domModel.isDirty() && f != null && f.isAccessible(); if (updateTasks) { // remove old JavaScript task markers try { IMarker[] foundMarkers = f.findMarkers(JAVASCRIPT_TASK_MARKER_TYPE, true, IResource.DEPTH_ONE); for (int i = 0; i < foundMarkers.length; i++) { foundMarkers[i].delete(); } } catch (CoreException e) { Logger.logException(e); } } // if(!inBatch) reporter.removeAllMessages(this, f); // add new messages for (int i = 0; i < problems.size() && !reporter.isCancelled(); i++) { IProblem problem = (IProblem) problems.get(i); IMessage m = createMessageFromProblem(problem, f, translation, domModel.getStructuredDocument()); if (m != null) { if (problem.getID() == IProblem.Task) { if (updateTasks) { // add new JavaScript task marker try { IMarker task = f.createMarker(JAVASCRIPT_TASK_MARKER_TYPE); task.setAttribute(IMarker.LINE_NUMBER, new Integer(m.getLineNumber())); task.setAttribute(IMarker.CHAR_START, new Integer(m.getOffset())); task.setAttribute(IMarker.CHAR_END, new Integer(m.getOffset() + m.getLength())); task.setAttribute(IMarker.MESSAGE, m.getText()); task.setAttribute(IMarker.USER_EDITABLE, Boolean.FALSE); switch (m.getSeverity()) { case IMessage.HIGH_SEVERITY: { task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_HIGH)); task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_ERROR)); } break; case IMessage.LOW_SEVERITY: { task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_LOW)); task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_INFO)); } break; default: { task.setAttribute(IMarker.PRIORITY, new Integer(IMarker.PRIORITY_NORMAL)); task.setAttribute(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING)); } } } catch (CoreException e) { Logger.logException(e); } } } else { reporter.addMessage(fMessageOriginator, m); } } } } } }
private void checkResourceFix(String name, String caretLocation, String expectedNewPath) throws Exception { IProject project = getProject(); IFile file = getTestDataFile(project, name, FD_RES + "/" + FD_RES_LAYOUT + "/" + name); // Determine the offset final int offset = getCaretOffset(file, caretLocation); String osRoot = project.getLocation().toOSString(); List<String> errors = new ArrayList<String>(); String fileRelativePath = file.getProjectRelativePath().toPortableString(); String filePath = osRoot + File.separator + fileRelativePath; // Run AaptParser such that markers are added... // When debugging these tests, the project gets a chance to build itself // so // the real aapt errors are there. But when the test is run directly, // aapt has // not yet run. I tried waiting for the build (using the code in // SampleProjectTest) // but this had various adverse effects (exception popups from the // Eclipse debugger // etc) so instead this test just hardcodes the aapt errors that should // be // observed on quickfix1.xml. assertEquals("Unit test is hardcoded to errors for quickfix1.xml", "quickfix1.xml", name); errors.add( filePath + ":7: error: Error: No resource found that matches the given name" + " (at 'text' with value '@string/firststring')."); errors.add( filePath + ":7: error: Error: No resource found that matches the given name" + " (at 'layout_width' with value '@dimen/testdimen')."); errors.add( filePath + ":13: error: Error: No resource found that matches the given name" + " (at 'layout' with value '@layout/testlayout')."); AaptParser.parseOutput(errors, project); AaptQuickFix aaptQuickFix = new AaptQuickFix(); // Open file IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); assertNotNull(page); IEditorPart editor = IDE.openEditor(page, file); assertTrue(editor instanceof AndroidXmlEditor); AndroidXmlEditor layoutEditor = (AndroidXmlEditor) editor; final ISourceViewer viewer = layoutEditor.getStructuredSourceViewer(); // Test marker resolution. IMarker[] markers = file.findMarkers(AndmoreAndroidConstants.MARKER_AAPT_COMPILE, true, IResource.DEPTH_ZERO); for (IMarker marker : markers) { int start = marker.getAttribute(IMarker.CHAR_START, 0); int end = marker.getAttribute(IMarker.CHAR_END, 0); if (offset >= start && offset <= end) { // Found the target marker. Now check the marker resolution of // it. assertTrue(aaptQuickFix.hasResolutions(marker)); IMarkerResolution[] resolutions = aaptQuickFix.getResolutions(marker); assertNotNull(resolutions); assertEquals(1, resolutions.length); IMarkerResolution resolution = resolutions[0]; assertNotNull(resolution); assertTrue(resolution.getLabel().contains("Create resource")); // Not running marker yet -- if we create the files here they // already // exist when the quick assist code runs. (The quick fix and the // quick assist // mostly share code for the implementation anyway.) // resolution.run(marker); break; } } // Next test quick assist. IQuickAssistInvocationContext invocationContext = new IQuickAssistInvocationContext() { @Override public int getLength() { return 0; } @Override public int getOffset() { return offset; } @Override public ISourceViewer getSourceViewer() { return viewer; } }; ICompletionProposal[] proposals = aaptQuickFix.computeQuickAssistProposals(invocationContext); assertNotNull(proposals); assertTrue(proposals.length == 1); ICompletionProposal proposal = proposals[0]; assertNotNull(proposal.getAdditionalProposalInfo()); assertNotNull(proposal.getImage()); assertTrue(proposal.getDisplayString().contains("Create resource")); IDocument document = new Document(); String fileContent = AndmoreAndroidPlugin.readFile(file); document.set(fileContent); // Apply quick fix proposal.apply(document); IPath path = new Path(expectedNewPath); IFile newFile = project.getFile(path); assertNotNull(path.toPortableString(), newFile); // Ensure that the newly created file was opened IEditorPart currentFile = AdtUtils.getActiveEditor(); assertEquals( newFile.getProjectRelativePath(), ((FileEditorInput) currentFile.getEditorInput()).getFile().getProjectRelativePath()); // Look up caret offset assertTrue( currentFile != null ? currentFile.getClass().getName() : "null", currentFile instanceof AndroidXmlEditor); AndroidXmlEditor newEditor = (AndroidXmlEditor) currentFile; ISourceViewer newViewer = newEditor.getStructuredSourceViewer(); Point selectedRange = newViewer.getSelectedRange(); String newFileContents = AndmoreAndroidPlugin.readFile(newFile); // Insert selection markers -- [ ] for the selection range, ^ for the // caret String newFileWithCaret = addSelection(newFileContents, selectedRange); newFileWithCaret = removeSessionData(newFileWithCaret); assertEqualsGolden(name, newFileWithCaret); }
private void checkNamespaceFix(String name, String caretLocation) throws Exception { IProject project = getProject(); IFile file = getTestDataFile(project, name, FD_RES + "/" + FD_RES_COLOR + "/" + name); // Determine the offset final int offset = getCaretOffset(file, caretLocation); String osRoot = project.getLocation().toOSString(); List<String> errors = new ArrayList<String>(); String fileRelativePath = file.getProjectRelativePath().toPortableString(); String filePath = osRoot + File.separator + fileRelativePath; assertEquals("Unit test is hardcoded to errors for quickfix2.xml", "quickfix2.xml", name); errors.add(filePath + ":5: error: Error parsing XML: unbound prefix"); AaptParser.parseOutput(errors, project); AaptQuickFix aaptQuickFix = new AaptQuickFix(); // Open file IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); assertNotNull(page); IEditorPart editor = IDE.openEditor(page, file); assertTrue(editor instanceof AndroidXmlEditor); AndroidXmlEditor layoutEditor = (AndroidXmlEditor) editor; final ISourceViewer viewer = layoutEditor.getStructuredSourceViewer(); // Test marker resolution. IMarker[] markers = file.findMarkers(AndmoreAndroidConstants.MARKER_AAPT_COMPILE, true, IResource.DEPTH_ZERO); assertEquals(1, markers.length); IMarker marker = markers[0]; // Found the target marker. Now check the marker resolution of it. assertTrue(aaptQuickFix.hasResolutions(marker)); IMarkerResolution[] resolutions = aaptQuickFix.getResolutions(marker); assertNotNull(resolutions); assertEquals(1, resolutions.length); IMarkerResolution resolution = resolutions[0]; assertNotNull(resolution); assertTrue(resolution.getLabel().contains("Insert namespace")); // Next test quick assist. IQuickAssistInvocationContext invocationContext = new IQuickAssistInvocationContext() { @Override public int getLength() { return 0; } @Override public int getOffset() { return offset; } @Override public ISourceViewer getSourceViewer() { return viewer; } }; ICompletionProposal[] proposals = aaptQuickFix.computeQuickAssistProposals(invocationContext); assertNotNull(proposals); assertTrue(proposals.length == 1); ICompletionProposal proposal = proposals[0]; assertNotNull(proposal.getAdditionalProposalInfo()); assertNotNull(proposal.getImage()); assertTrue(proposal.getDisplayString().contains("Insert namespace")); // Open the file to ensure we can get an XML model with // getExistingModelForEdit: AndmoreAndroidPlugin.openFile(file, null); IEditorPart newEditor = AdtUtils.getActiveEditor(); assertTrue(newEditor instanceof AndroidXmlEditor); AndroidXmlEditor xmlEditor = (AndroidXmlEditor) newEditor; IDocument document = xmlEditor.getStructuredSourceViewer().getDocument(); // Apply quick fix String before = document.get(); proposal.apply(document); String after = document.get(); String diff = getDiff(before, after); assertEqualsGolden(name, diff); }
public void testUPCartifacts() throws Exception { System.out.println("\n==> " + getMethodName() + "()..."); IFile file = importFile("resources", "testUPC.upc"); assertNotNull(file); IFile upcInclude = importFile("resources/includes", "upc.h"); assertNotNull(upcInclude); String tempPath = upcInclude.getFullPath().toOSString(); // includePath= /RegressionTestProject/upc.h System.out.println("tempPath=" + tempPath); String includePath = upcInclude.getWorkspace().getRoot().getRawLocation().toOSString() + upcInclude.getFullPath().toFile().getAbsolutePath(); System.out.println("includePath= " + includePath); assertTrue(file instanceof IAdaptable); CoreModel.getDefault().getCModel().makeConsistent(new NullProgressMonitor()); // jeff assertNotNull(cproject); ICElement ce = cproject.findElement(file.getFullPath()); // ICElement covers folders and translationunits // final ICElement ce = (ICElement) ((IAdaptable)file).getAdapter(ICElement.class); assertNotNull(ce); List<String> includes = Arrays.asList(new String[] {includePath}); RunAnalyseUPCcommandHandler racm = new RunAnalyseUPCcommandHandler(); racm.runResource(new NullProgressMonitor(), ce, 0, includes); IMarker[] markers = file.findMarkers(UPCIDs.MARKER_ID, true, IResource.DEPTH_INFINITE); assertNotNull(markers); System.out.println("numMarkers: " + markers.length); // need to sort markers, since they are not returned in a pre-determined order?? for (int i = 0; i < markers.length; i++) { IMarker marker = markers[i]; int lineNo = (Integer) marker.getAttribute(IMarker.LINE_NUMBER); System.out.println( i + " marker: lineNo " + lineNo + " name: " + marker.getAttribute(IDs.NAME)); } // When strings don't match, click on the first entry (ComparisonFailure) in the Failure Trace // in the JUnit view to get a // diff view // assertEquals("This\nis\na\ntest", "This\nwas\na\ntest"); int[] expectedLinenos = {77}; String[] expectedTypes = {"upc_addrfield"}; ArtifactWithLine[] expectedArts = new ArtifactWithLine[expectedLinenos.length]; ArtifactWithLine[] markerArts = new ArtifactWithLine[markers.length]; for (int i = 0; i < expectedArts.length; i++) { expectedArts[i] = new ArtifactWithLine(expectedLinenos[i], expectedTypes[i]); } for (int i = 0; i < markerArts.length; i++) { markerArts[i] = new ArtifactWithLine(markers[i]); } Arrays.sort(expectedArts); Arrays.sort(markerArts); assertEquals(expectedArts.length, markerArts.length); // Since these tests are in a loop, if one fails, must inspect the Console output to know which // ones finished and which one // failed. for (int i = 0; i < markers.length; i++) { // Marker should be on the line number we expect System.out.println( i + ". " + expectedArts[i].getLineNo() + " = " + markerArts[i].getLineNo()); assertEquals(expectedArts[i].getLineNo(), markerArts[i].getLineNo()); // Marker should be of the type name we expect System.out.println(" " + expectedArts[i].getName() + " = " + markerArts[i].getName()); assertEquals(expectedArts[i].getName(), markerArts[i].getName()); // the following never works, so we'll be happy enough with the two assertEquals above. // assertEquals(expectedArts[i], markerArts[i]); } }