diff options
Diffstat (limited to 'bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation')
11 files changed, 0 insertions, 3505 deletions
diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/FragmentValidationTools.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/FragmentValidationTools.java deleted file mode 100644 index 83a95abb1e..0000000000 --- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/FragmentValidationTools.java +++ /dev/null @@ -1,57 +0,0 @@ -/*******************************************************************************
- * Copyright (c) 2008 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.jst.jsp.core.internal.validation;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ProjectScope;
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.jst.jsp.core.internal.JSPCorePlugin;
-import org.eclipse.jst.jsp.core.internal.preferences.JSPCorePreferenceNames;
-
-
-/**
- * Utility class for reading fragment validation preferences/properties.
- * JSPFContentProperties does not respect the project override preference.
- *
- */
-class FragmentValidationTools {
- /**
- * @param resource
- * @return whether to perform validation on a fragment, returning the
- * project-specific preference only of project-specific values are
- * enabled
- */
- static boolean shouldValidateFragment(IResource resource) {
- String qualifier = JSPCorePlugin.getDefault().getBundle().getSymbolicName();
-
- IProject project = null;
- if (resource.getType() == IResource.PROJECT) {
- project = (IProject) resource;
- }
- else {
- project = resource.getProject();
- }
- if (project != null) {
- IEclipsePreferences node = new ProjectScope(project).getNode(qualifier);
- // first, check whether project specific settings are to be used
- boolean useProjectSettings = node.getBoolean(JSPCorePreferenceNames.VALIDATION_USE_PROJECT_SETTINGS, false);
- if (useProjectSettings) {
- // only if so, return that value
- return node.getBoolean(JSPCorePreferenceNames.VALIDATE_FRAGMENTS, true);
- }
- // if not, return the workspace value
- }
- return new InstanceScope().getNode(qualifier).getBoolean(JSPCorePreferenceNames.VALIDATE_FRAGMENTS, true);
- }
-}
diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/HTMLValidationReporter.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/HTMLValidationReporter.java deleted file mode 100644 index 1c77c11008..0000000000 --- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/HTMLValidationReporter.java +++ /dev/null @@ -1,108 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.jsp.core.internal.validation; - -import org.eclipse.core.resources.IFile; -import org.eclipse.wst.html.core.internal.validate.MessageFactory; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.validate.ErrorInfo; -import org.eclipse.wst.sse.core.internal.validate.ValidationMessage; -import org.eclipse.wst.sse.core.internal.validate.ValidationReporter; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; - -/* - * Copied from html.ui's HTMLValidationReporter with some minor cleanup - * modifications - */ -class HTMLValidationReporter implements ValidationReporter { - - private IValidator owner = null; - private IReporter reporter = null; - private IFile file = null; - private IStructuredModel model = null; - private MessageFactory fFactory = null; - - /** - */ - public HTMLValidationReporter(IValidator owner, IReporter reporter, IFile file, IStructuredModel model) { - super(); - this.owner = owner; - this.reporter = reporter; - this.file = file; - this.model = model; - fFactory = new MessageFactory(file != null ? file.getProject() : null); - } - - /** - */ - public void clear() { - if (this.file == null) - return; - - - if (this.reporter != null) { - this.reporter.removeAllMessages(this.owner, this.file); - } - } - - - - /** - */ - public void report(ValidationMessage message) { - if (message == null || this.file == null || message.getSeverity() == ValidationMessage.IGNORE) - return; - IMessage mes = translateMessage(message); - - if (this.reporter != null) { - this.reporter.addMessage(this.owner, mes); - } - } - - /** - * Translate ValidationMessage to IMessage and generate result log - */ - private IMessage translateMessage(ValidationMessage message) { - int severity = IMessage.LOW_SEVERITY; - switch (message.getSeverity()) { - case ValidationMessage.ERROR : - severity = IMessage.HIGH_SEVERITY; - break; - case ValidationMessage.WARNING : - severity = IMessage.NORMAL_SEVERITY; - break; - case ValidationMessage.INFORMATION : - break; - default : - break; - } - - IMessage mes = new LocalizedMessage(severity, message.getMessage(), this.file); - mes.setOffset(message.getOffset()); - mes.setLength(message.getLength()); - if (this.model != null) { - IStructuredDocument flatModel = this.model.getStructuredDocument(); - if (flatModel != null) { - int line = flatModel.getLineOfOffset(message.getOffset()); - mes.setLineNo(line + 1); - } - } - - return mes; - } - - public void report(ErrorInfo info) { - report(fFactory.createMessage(info)); - } -} diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPActionValidator.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPActionValidator.java deleted file mode 100644 index ad213e192a..0000000000 --- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPActionValidator.java +++ /dev/null @@ -1,469 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2008, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.jsp.core.internal.validation; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.ProjectScope; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.preferences.DefaultScope; -import org.eclipse.core.runtime.preferences.IPreferencesService; -import org.eclipse.core.runtime.preferences.IScopeContext; -import org.eclipse.core.runtime.preferences.InstanceScope; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.jst.jsp.core.internal.JSPCoreMessages; -import org.eclipse.jst.jsp.core.internal.JSPCorePlugin; -import org.eclipse.jst.jsp.core.internal.Logger; -import org.eclipse.jst.jsp.core.internal.contentmodel.TaglibController; -import org.eclipse.jst.jsp.core.internal.contentmodel.tld.TLDCMDocumentManager; -import org.eclipse.jst.jsp.core.internal.contentmodel.tld.TaglibTracker; -import org.eclipse.jst.jsp.core.internal.contentmodel.tld.provisional.TLDAttributeDeclaration; -import org.eclipse.jst.jsp.core.internal.contentmodel.tld.provisional.TLDElementDeclaration; -import org.eclipse.jst.jsp.core.internal.contenttype.DeploymentDescriptorPropertyCache; -import org.eclipse.jst.jsp.core.internal.contenttype.DeploymentDescriptorPropertyCache.PropertyGroup; -import org.eclipse.jst.jsp.core.internal.document.PageDirectiveAdapter; -import org.eclipse.jst.jsp.core.internal.document.PageDirectiveAdapterImpl; -import org.eclipse.jst.jsp.core.internal.preferences.JSPCorePreferenceNames; -import org.eclipse.jst.jsp.core.internal.regions.DOMJSPRegionContexts; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionContainer; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; -import org.eclipse.wst.sse.core.internal.validate.ValidationMessage; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; -import org.eclipse.wst.xml.core.internal.contentmodel.CMAttributeDeclaration; -import org.eclipse.wst.xml.core.internal.contentmodel.CMElementDeclaration; -import org.eclipse.wst.xml.core.internal.contentmodel.CMNamedNodeMap; -import org.eclipse.wst.xml.core.internal.contentmodel.CMNode; -import org.eclipse.wst.xml.core.internal.contentmodel.basic.CMNamedNodeMapImpl; -import org.eclipse.wst.xml.core.internal.contentmodel.modelquery.ModelQuery; -import org.eclipse.wst.xml.core.internal.modelquery.ModelQueryUtil; -import org.eclipse.wst.xml.core.internal.provisional.contentmodel.CMNodeWrapper; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMAttr; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode; -import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext; -import org.w3c.dom.Attr; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.NodeList; - -/** - * Checks for: missing required attributes & undefined attributes in jsp - * action tags such as jsp directives and jsp custom tags as well as non-empty - * inline jsp action tags - */ -public class JSPActionValidator extends JSPValidator { - /** - * - */ - private static final String PREFERENCE_NODE_QUALIFIER = JSPCorePlugin.getDefault().getBundle().getSymbolicName(); - private IValidator fMessageOriginator; - private IPreferencesService fPreferencesService = null; - private IScopeContext[] fScopes = null; - private int fSeverityMissingRequiredAttribute = IMessage.HIGH_SEVERITY; - private int fSeverityNonEmptyInlineTag = IMessage.NORMAL_SEVERITY; - private int fSeverityUnknownAttribute = IMessage.NORMAL_SEVERITY; - private int fSeverityUnexpectedRuntimeExpression = IMessage.NORMAL_SEVERITY; - - private HashSet fTaglibPrefixes = new HashSet(); - private boolean fIsELIgnored = false; - - public JSPActionValidator() { - this.fMessageOriginator = this; - } - - public JSPActionValidator(IValidator validator) { - this.fMessageOriginator = validator; - } - - private void checkNonEmptyInlineTag(IDOMElement element, CMElementDeclaration cmElementDecl, IReporter reporter, IFile file, IStructuredDocument document) { - if (cmElementDecl.getContentType() == CMElementDeclaration.EMPTY && element.getChildNodes().getLength() > 0) { - String msgText = NLS.bind(JSPCoreMessages.JSPActionValidator_0, element.getNodeName()); - LocalizedMessage message = new LocalizedMessage(fSeverityNonEmptyInlineTag, msgText, file); - int start = element.getStartOffset(); - int length = element.getStartEndOffset() - start; - int lineNo = document.getLineOfOffset(start); - message.setLineNo(lineNo); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - } - - /** - * Checks an attribute for runtime expressions - * @param a The attribute to check for runtime expressions - * @return true if the attribute contains a runtime expression, false otherwise - */ - private boolean checkRuntimeValue(IDOMAttr a) { - ITextRegion value = a.getValueRegion(); - if (value instanceof ITextRegionContainer) { - Iterator it = ((ITextRegionContainer) value).getRegions().iterator(); - while (it.hasNext()) { - String type = ((ITextRegion) it.next()).getType(); - if (type == DOMJSPRegionContexts.JSP_EL_OPEN) - return true; - } - } - return false; - } - - /** - * Determines if EL should be ignored. Checks - * <ol> - * <li>JSP version</li> - * <li>Page directive isELIgnored</li> - * <li>Deployment descriptor's el-ignored</li> - * </ol> - * @return true if EL should be ignored, false otherwise. If the JSP version is < 2.0, EL is ignored by default - */ - private boolean isElIgnored(IPath path, IStructuredModel model) { - if (DeploymentDescriptorPropertyCache.getInstance().getJSPVersion(path) < 2.0f) - return true; - String directiveIsELIgnored = ((PageDirectiveAdapterImpl)(((IDOMModel) model).getDocument().getAdapterFor(PageDirectiveAdapter.class))).getElIgnored(); - // isELIgnored directive found - if (directiveIsELIgnored != null) - return Boolean.valueOf(directiveIsELIgnored).booleanValue(); - // Check the deployment descriptor for el-ignored - PropertyGroup[] groups = DeploymentDescriptorPropertyCache.getInstance().getPropertyGroups(path); - if (groups.length > 0) - return groups[0].isELignored(); - // JSP version >= 2.0 defaults to evaluating EL - return false; - } - - private void checkRequiredAttributes(IDOMElement element, CMNamedNodeMap attrMap, IReporter reporter, IFile file, IStructuredDocument document, IStructuredDocumentRegion documentRegion) { - Iterator it = attrMap.iterator(); - CMAttributeDeclaration attr = null; - while (it.hasNext()) { - attr = (CMAttributeDeclaration) it.next(); - if (attr.getUsage() == CMAttributeDeclaration.REQUIRED) { - Attr a = element.getAttributeNode(attr.getAttrName()); - if (a == null) { - // Attribute may be defined using a jsp:attribute action - if (!checkJSPAttributeAction(element, attr)) { - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_5, attr.getAttrName()); - LocalizedMessage message = new LocalizedMessage(fSeverityMissingRequiredAttribute, msgText, file); - int start = element.getStartOffset(); - int length = element.getStartEndOffset() - start; - int lineNo = document.getLineOfOffset(start); - message.setLineNo(lineNo); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - } - } - } - } - - /** - * Checks for jsp:attribute actions of <code>element</code> to see if they - * satisfy the required attribute <code>attr</code> - * - * @param element The element with a required attribute - * @param attr The required attribute - * @return <code>true</code> if a jsp:attribute action has the name of - * the required attribute <code>attr</code>; <code>false</code> otherwise. - */ - private boolean checkJSPAttributeAction(IDOMElement element, CMAttributeDeclaration attr) { - if (element != null && attr != null) { - NodeList elements = element.getElementsByTagName("jsp:attribute"); //$NON-NLS-1$ - String neededAttrName = attr.getNodeName(); - for (int i = 0; i < elements.getLength(); i++) { - Element childElement = (Element) elements.item(i); - /* - * Get the name attribute of jsp:attribute and compare its - * value to the required attribute name - */ - if (childElement.hasAttribute("name") && neededAttrName.equals(childElement.getAttribute("name"))) {//$NON-NLS-1$ //$NON-NLS-2$ - return true; - } - } - } - return false; - } - - private boolean checkUnknownAttributes(IDOMElement element, CMElementDeclaration elementDecl, CMNamedNodeMap cmAttrs, IReporter reporter, IFile file, IStructuredDocument document, IStructuredDocumentRegion documentRegion) { - boolean foundjspattribute = false; - boolean dynamicAttributesAllowed = false; - CMElementDeclaration decl = elementDecl; - if (decl instanceof CMNodeWrapper) - decl = (CMElementDeclaration) ((CMNodeWrapper) decl).getOriginNode(); - if (decl instanceof TLDElementDeclaration) { - String dynamicAttributes = ((TLDElementDeclaration) decl).getDynamicAttributes(); - dynamicAttributesAllowed = dynamicAttributes != null ? Boolean.valueOf(dynamicAttributes).booleanValue() : false; - } - - NamedNodeMap attrs = element.getAttributes(); - for (int i = 0; i < attrs.getLength(); i++) { - Attr a = (Attr) attrs.item(i); - CMAttributeDeclaration adec = (CMAttributeDeclaration) cmAttrs.getNamedItem(a.getName()); - if (adec == null) { - /* - * No attr declaration was found. That is, the attr name is - * undefined. Disregard it includes JSP structure or this - * element supports dynamic attributes - */ - if (!hasJSPRegion(((IDOMNode) a).getNameRegion()) && fSeverityUnknownAttribute != ValidationMessage.IGNORE) { - if (!dynamicAttributesAllowed) { - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_6, a.getName()); - LocalizedMessage message = new LocalizedMessage(fSeverityUnknownAttribute, msgText, file); - int start = ((IDOMAttr) a).getNameRegionStartOffset(); - int length = ((IDOMAttr) a).getNameRegionEndOffset() - start; - int lineNo = document.getLineOfOffset(start); - message.setLineNo(lineNo); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - } - else { - foundjspattribute = true; - } - } - else { - if (fSeverityUnexpectedRuntimeExpression != ValidationMessage.IGNORE && adec instanceof TLDAttributeDeclaration) { - // The attribute cannot have a runtime evaluation of an expression - if (!Boolean.valueOf(((TLDAttributeDeclaration) adec).getRtexprvalue()).booleanValue()) { - IDOMAttr attr = (IDOMAttr) a; - if(checkRuntimeValue(attr) && !fIsELIgnored) { - String msg = NLS.bind(JSPCoreMessages.JSPActionValidator_1, a.getName()); - LocalizedMessage message = new LocalizedMessage(fSeverityUnexpectedRuntimeExpression, msg, file); - ITextRegion region = attr.getValueRegion(); - int start = attr.getValueRegionStartOffset(); - int length = region != null ? region.getTextLength() : 0; - int lineNo = document.getLineOfOffset(start); - message.setLineNo(lineNo); - message.setOffset(start); - message.setLength(length); - reporter.addMessage(fMessageOriginator, message); - } - } - } - } - } - return foundjspattribute; - } - - public void cleanup(IReporter reporter) { - super.cleanup(reporter); - fTaglibPrefixes.clear(); - } - - int getMessageSeverity(String key) { - int sev = fPreferencesService.getInt(PREFERENCE_NODE_QUALIFIER, key, IMessage.NORMAL_SEVERITY, fScopes); - switch (sev) { - case ValidationMessage.ERROR : - return IMessage.HIGH_SEVERITY; - case ValidationMessage.WARNING : - return IMessage.NORMAL_SEVERITY; - case ValidationMessage.INFORMATION : - return IMessage.LOW_SEVERITY; - case ValidationMessage.IGNORE : - return ValidationMessage.IGNORE; - } - return IMessage.NORMAL_SEVERITY; - } - - private String getStartTagName(IStructuredDocumentRegion sdr) { - String name = new String(); - ITextRegionList subRegions = sdr.getRegions(); - if (subRegions.size() > 2) { - ITextRegion subRegion = subRegions.get(0); - if (subRegion.getType() == DOMRegionContext.XML_TAG_OPEN) { - subRegion = subRegions.get(1); - if (subRegion.getType() == DOMRegionContext.XML_TAG_NAME) { - name = sdr.getText(subRegion); - } - } - } - return name; - } - - private HashSet getTaglibPrefixes(IStructuredDocument document) { - if (fTaglibPrefixes.isEmpty()) { - // add all reserved prefixes - fTaglibPrefixes.add("jsp"); //$NON-NLS-1$ - fTaglibPrefixes.add("jspx"); //$NON-NLS-1$ - fTaglibPrefixes.add("java"); //$NON-NLS-1$ - fTaglibPrefixes.add("javax"); //$NON-NLS-1$ - fTaglibPrefixes.add("servlet"); //$NON-NLS-1$ - fTaglibPrefixes.add("sun"); //$NON-NLS-1$ - fTaglibPrefixes.add("sunw"); //$NON-NLS-1$ - - // add all taglib prefixes - TLDCMDocumentManager manager = TaglibController.getTLDCMDocumentManager(document); - if (manager != null) { - List trackers = manager.getTaglibTrackers(); - for (Iterator it = trackers.iterator(); it.hasNext();) { - TaglibTracker tracker = (TaglibTracker) it.next(); - String prefix = tracker.getPrefix(); - fTaglibPrefixes.add(prefix); - } - } - } - return fTaglibPrefixes; - } - - private boolean hasJSPRegion(ITextRegion container) { - if (!(container instanceof ITextRegionContainer)) - return false; - ITextRegionList regions = ((ITextRegionContainer) container).getRegions(); - if (regions == null) - return false; - Iterator e = regions.iterator(); - while (e.hasNext()) { - ITextRegion region = (ITextRegion) e.next(); - if (region == null) - continue; - String regionType = region.getType(); - if (regionType == DOMRegionContext.XML_TAG_OPEN || (isNestedTagName(regionType))) - return true; - } - return false; - } - - private boolean isNestedTagName(String regionType) { - boolean result = regionType.equals(DOMJSPRegionContexts.JSP_SCRIPTLET_OPEN) || regionType.equals(DOMJSPRegionContexts.JSP_EXPRESSION_OPEN) || regionType.equals(DOMJSPRegionContexts.JSP_DECLARATION_OPEN) || regionType.equals(DOMJSPRegionContexts.JSP_DIRECTIVE_OPEN); - return result; - } - - private void loadPreferences(IFile file) { - fScopes = new IScopeContext[]{new InstanceScope(), new DefaultScope()}; - - fPreferencesService = Platform.getPreferencesService(); - if (file != null && file.isAccessible()) { - ProjectScope projectScope = new ProjectScope(file.getProject()); - if (projectScope.getNode(PREFERENCE_NODE_QUALIFIER).getBoolean(JSPCorePreferenceNames.VALIDATION_USE_PROJECT_SETTINGS, false)) { - fScopes = new IScopeContext[]{projectScope, new InstanceScope(), new DefaultScope()}; - } - } - - fSeverityMissingRequiredAttribute = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_ACTIONS_SEVERITY_MISSING_REQUIRED_ATTRIBUTE); - fSeverityNonEmptyInlineTag = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_ACTIONS_SEVERITY_NON_EMPTY_INLINE_TAG); - fSeverityUnknownAttribute = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_ACTIONS_SEVERITY_UNKNOWN_ATTRIBUTE); - fSeverityUnexpectedRuntimeExpression = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_ACTIONS_SEVERITY_UNEXPECTED_RTEXPRVALUE); - } - - void performValidation(IFile f, IReporter reporter, IStructuredModel model) { - fTaglibPrefixes.clear(); - int length = model.getStructuredDocument().getLength(); - performValidation(f, reporter, model, new Region(0, length)); - } - - protected void performValidation(IFile f, IReporter reporter, IStructuredModel model, IRegion validateRegion) { - loadPreferences(f); - IStructuredDocument sDoc = model.getStructuredDocument(); - - fIsELIgnored = isElIgnored(f.getFullPath(), model); - // iterate all document regions - IStructuredDocumentRegion region = sDoc.getRegionAtCharacterOffset(validateRegion.getOffset()); - while (region != null && !reporter.isCancelled() && (region.getStartOffset() <= (validateRegion.getOffset() + validateRegion.getLength()))) { - if (region.getType() == DOMJSPRegionContexts.JSP_DIRECTIVE_NAME) { - // only checking directives - processDirective(reporter, f, model, region); - fTaglibPrefixes.clear(); - } - else if (region.getType() == DOMRegionContext.XML_TAG_NAME) { - // and jsp tags - String tagName = getStartTagName(region); - int colonPosition = tagName.indexOf(':'); - if (colonPosition > -1) { - // get tag's prefix and check if it's really a jsp action - // tag - String prefix = tagName.substring(0, colonPosition); - if (getTaglibPrefixes(sDoc).contains(prefix)) - processDirective(reporter, f, model, region); - } - } - region = region.getNext(); - } - unloadPreferences(); - } - - private void processDirective(IReporter reporter, IFile file, IStructuredModel model, IStructuredDocumentRegion documentRegion) { - IndexedRegion ir = model.getIndexedRegion(documentRegion.getStartOffset()); - if (ir instanceof IDOMElement) { - IDOMElement element = (IDOMElement) ir; - ModelQuery query = ModelQueryUtil.getModelQuery(model); - if (query != null) { - CMElementDeclaration cmElement = query.getCMElementDeclaration(element); - if (cmElement != null) { - CMNamedNodeMap cmAttributes = null; - - CMNamedNodeMapImpl allAttributes = new CMNamedNodeMapImpl(); - List nodes = query.getAvailableContent(element, cmElement, ModelQuery.INCLUDE_ATTRIBUTES); - for (int k = 0; k < nodes.size(); k++) { - CMNode cmnode = (CMNode) nodes.get(k); - if (cmnode.getNodeType() == CMNode.ATTRIBUTE_DECLARATION) { - allAttributes.put(cmnode); - } - } - cmAttributes = allAttributes; - - boolean foundjspattribute = checkUnknownAttributes(element, cmElement, cmAttributes, reporter, file, model.getStructuredDocument(), documentRegion); - // required attributes could be hidden in jsp regions in - // tags, so if jsp regions were detected, do not check for - // missing required attributes - if (!foundjspattribute && fSeverityMissingRequiredAttribute != ValidationMessage.IGNORE) - checkRequiredAttributes(element, cmAttributes, reporter, file, model.getStructuredDocument(), documentRegion); - - if (fSeverityNonEmptyInlineTag != ValidationMessage.IGNORE) - checkNonEmptyInlineTag(element, cmElement, reporter, file, model.getStructuredDocument()); - } - } - } - } - - private void unloadPreferences() { - fPreferencesService = null; - fScopes = null; - } - - protected void validateFile(IFile f, IReporter reporter) { - if (DEBUG) { - Logger.log(Logger.INFO, getClass().getName() + " validating: " + f); //$NON-NLS-1$ - } - - IStructuredModel sModel = null; - try { - sModel = StructuredModelManager.getModelManager().getModelForRead(f); - if (sModel != null && !reporter.isCancelled()) { - performValidation(f, reporter, sModel); - } - } - catch (Exception e) { - Logger.logException(e); - } - finally { - if (sModel != null) - sModel.releaseFromRead(); - } - } -} diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPBatchValidator.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPBatchValidator.java deleted file mode 100644 index 42c287b3e4..0000000000 --- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPBatchValidator.java +++ /dev/null @@ -1,539 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.jst.jsp.core.internal.validation; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceProxy; -import org.eclipse.core.resources.IResourceProxyVisitor; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExecutableExtension; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.jobs.ISchedulingRule; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jst.jsp.core.internal.JSPCoreMessages; -import org.eclipse.jst.jsp.core.internal.Logger; -import org.eclipse.jst.jsp.core.internal.contenttype.DeploymentDescriptorPropertyCache; -import org.eclipse.jst.jsp.core.internal.contenttype.DeploymentDescriptorPropertyCache.PropertyGroup; -import org.eclipse.jst.jsp.core.internal.provisional.contenttype.ContentTypeIdForJSP; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.validation.AbstractValidator; -import org.eclipse.wst.validation.ValidationResult; -import org.eclipse.wst.validation.ValidationState; -import org.eclipse.wst.validation.internal.ConfigurationManager; -import org.eclipse.wst.validation.internal.ProjectConfiguration; -import org.eclipse.wst.validation.internal.ValidationRegistryReader; -import org.eclipse.wst.validation.internal.core.Message; -import org.eclipse.wst.validation.internal.core.ValidationException; -import org.eclipse.wst.validation.internal.operations.IWorkbenchContext; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidationContext; -import org.eclipse.wst.validation.internal.provisional.core.IValidatorJob; - -/** - * Performs JSP validation tasks for batch validation. The individual - * validator classes will still be used for source validation. - */ -public final class JSPBatchValidator extends AbstractValidator implements IValidatorJob, IExecutableExtension { - class JSPFileVisitor implements IResourceProxyVisitor { - - private List fFiles = new ArrayList(); - private IReporter fReporter = null; - - public JSPFileVisitor(IReporter reporter) { - fReporter = reporter; - } - - final IFile[] getFiles() { - return (IFile[]) fFiles.toArray(new IFile[fFiles.size()]); - } - - public boolean visit(IResourceProxy proxy) throws CoreException { - - // check validation - if (fReporter.isCancelled()) - return false; - - if (proxy.getType() == IResource.FILE) { - - if (isJSPType(proxy.getName()) && proxy.isAccessible()) { - IFile file = (IFile) proxy.requestResource(); - if (DEBUG) - System.out.println("(+) JSPValidator adding file: " + file.getName()); //$NON-NLS-1$ - fFiles.add(file); - - // don't search deeper for files - return false; - } - } - return true; - } - } - - // for debugging - static final boolean DEBUG = Boolean.valueOf(Platform.getDebugOption("org.eclipse.jst.jsp.core/debug/jspvalidator")).booleanValue(); //$NON-NLS-1$ - - private static final String PLUGIN_ID_JSP_CORE = "org.eclipse.jst.jsp.core"; //$NON-NLS-1$ - - /** - * List of IResources that the currently validating file depends upon - */ - private Collection fDependsOn; - - /** - * Gets current validation project configuration based on current project - * (which is based on current document) - * - * @return ProjectConfiguration - */ - static private ProjectConfiguration getProjectConfiguration(IFile file) { - ProjectConfiguration projectConfiguration = null; - if (file != null) { - IProject project = file.getProject(); - if (project != null) { - try { - projectConfiguration = ConfigurationManager.getManager().getProjectConfiguration(project); - } - catch (InvocationTargetException e) { - Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e); - } - } - } - - return projectConfiguration; - } - - /** - * Checks if validator is enabled according in Validation preferences - * - * @param vmd - * @return - */ - static boolean isBatchValidatorPreferenceEnabled(IFile file) { - if (file == null) { - return true; - } - - boolean enabled = true; - ProjectConfiguration configuration = getProjectConfiguration(file); - if (configuration != null) { - org.eclipse.wst.validation.internal.ValidatorMetaData metadata = ValidationRegistryReader.getReader().getValidatorMetaData(JSPBatchValidator.class.getName()); - if (configuration != null && metadata != null) { - if (!configuration.isBuildEnabled(metadata) && !configuration.isManualEnabled(metadata)) - enabled = false; - } - } - return enabled; - } - - String fAdditionalContentTypesIDs[] = null; - - private IContentType[] fContentTypes = null; - - private JSPDirectiveValidator fJSPDirectiveValidator = new JSPDirectiveValidator(this); - - private JSPELValidator fJSPELValidator = new JSPELValidator(this); - - private IContentType fJSPFContentType = null; - - private JSPJavaValidator fJSPJavaValidator = new JSPJavaValidator(this); - - private JSPActionValidator fJSPActionValidator = new JSPActionValidator(this); - - void addDependsOn(IResource resource) { - if(resource != null) { - fDependsOn.add(resource); - } - } - - public void cleanup(IReporter reporter) { - fJSPDirectiveValidator.cleanup(reporter); - fJSPELValidator.cleanup(reporter); - fJSPJavaValidator.cleanup(reporter); - fJSPActionValidator.cleanup(reporter); - } - - - void doValidate(IValidationContext helper, IReporter reporter) throws ValidationException { - String[] uris = helper.getURIs(); - if (uris.length > 0) { - IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); - IFile currentFile = null; - for (int i = 0; i < uris.length && !reporter.isCancelled(); i++) { - currentFile = wsRoot.getFile(new Path(uris[i])); - if (currentFile != null && currentFile.exists()) { - if (shouldValidate(currentFile) && fragmentCheck(currentFile)) { - Message message = new LocalizedMessage(IMessage.LOW_SEVERITY, currentFile.getFullPath().toString().substring(1)); - reporter.displaySubtask(this, message); - validateFile(currentFile, reporter); - } - if (DEBUG) - System.out.println("validating: [" + uris[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - else { - // if uris[] length 0 -> validate() gets called for each project - if (helper instanceof IWorkbenchContext) { - IProject project = ((IWorkbenchContext) helper).getProject(); - - Message message = new LocalizedMessage(IMessage.LOW_SEVERITY, NLS.bind(JSPCoreMessages.JSPBatchValidator_0, project.getFullPath())); - reporter.displaySubtask(this, message); - - JSPFileVisitor visitor = new JSPFileVisitor(reporter); - try { - // collect all jsp files for the project - project.accept(visitor, IResource.DEPTH_INFINITE); - } - catch (CoreException e) { - if (DEBUG) - e.printStackTrace(); - } - IFile[] files = visitor.getFiles(); - for (int i = 0; i < files.length && !reporter.isCancelled(); i++) { - if (shouldValidate(files[i]) && fragmentCheck(files[i])) { - - message = new LocalizedMessage(IMessage.LOW_SEVERITY, files[i].getFullPath().toString().substring(1)); - reporter.displaySubtask(this, message); - - validateFile(files[i], reporter); - } - if (DEBUG) - System.out.println("validating: [" + files[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - } - - /** - * Checks if file is a jsp fragment or not. If so, check if the fragment - * should be validated or not. - * - * @param file - * Assumes shouldValidate was already called on file so it - * should not be null and does exist - * @return false if file is a fragment and it should not be validated, - * true otherwise - */ - private boolean fragmentCheck(IFile file) { - boolean shouldValidate = true; - // quick check to see if this is possibly a jsp fragment - if (getJSPFContentType().isAssociatedWith(file.getName())) { - // get preference for validate jsp fragments - boolean shouldValidateFragments = FragmentValidationTools.shouldValidateFragment(file); - /* - * if jsp fragments should not be validated, check if file is - * really jsp fragment - */ - if (!shouldValidateFragments) { - boolean isFragment = isFragment(file); - shouldValidate = !isFragment; - } - } - return shouldValidate; - } - - /** - * Returns JSP fragment content type - * - * @return jspf content type - */ - private IContentType getJSPFContentType() { - if (fJSPFContentType == null) { - fJSPFContentType = Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT); - } - return fJSPFContentType; - } - - public ISchedulingRule getSchedulingRule(IValidationContext helper) { - if (helper instanceof IWorkbenchContext) { - /* - * Use a single build rule when running batch validation. - */ - return ResourcesPlugin.getWorkspace().getRuleFactory().buildRule(); - } - /* - * For other kinds of validation, use no specific rule - */ - return null; - } - - /** - * Gets list of content types this visitor is interested in - * - * @return All JSP-related content types - */ - private IContentType[] getValidContentTypes() { - if (fContentTypes == null) { - // currently "hard-coded" to be jsp & jspf - fContentTypes = new IContentType[]{Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSP), Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT)}; - if (fAdditionalContentTypesIDs != null) { - List allTypes = new ArrayList(Arrays.asList(fContentTypes)); - for (int i = 0; i < fAdditionalContentTypesIDs.length; i++) { - IContentType type = Platform.getContentTypeManager().getContentType(fAdditionalContentTypesIDs[i]); - if (type != null) { - allTypes.add(type); - } - } - fContentTypes = (IContentType[]) allTypes.toArray(new IContentType[allTypes.size()]); - } - } - return fContentTypes; - } - - /** - * Determines if file is jsp fragment or not (does a deep, indepth check, - * looking into contents of file) - * - * @param file - * assumes file is not null and exists - * @return true if file is jsp fragment, false otherwise - */ - private boolean isFragment(IFile file) { - boolean isFragment = false; - InputStream is = null; - try { - IContentDescription contentDescription = file.getContentDescription(); - // it can be null - if (contentDescription == null) { - is = file.getContents(); - contentDescription = Platform.getContentTypeManager().getDescriptionFor(is, file.getName(), new QualifiedName[]{IContentDescription.CHARSET}); - } - if (contentDescription != null) { - String fileCtId = contentDescription.getContentType().getId(); - isFragment = (fileCtId != null && ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT.equals(fileCtId)); - } - } - catch (IOException e) { - // ignore, assume it's invalid JSP - } - catch (CoreException e) { - // ignore, assume it's invalid JSP - } - finally { - /* - * must close input stream in case others need it - * (IFile.getContents() requirement as well) - */ - if (is != null) - try { - is.close(); - } - catch (Exception e) { - // not sure how to recover at this point - } - } - return isFragment; - } - - /** - * Checks if fileName is some type of JSP (including JSP fragments) - * - * @param fileName - * @return true if filename indicates some type of JSP, false otherwise - */ - private boolean isJSPType(String fileName) { - boolean valid = false; - - IContentType[] types = getValidContentTypes(); - int i = 0; - while (i < types.length && !valid) { - valid = types[i].isAssociatedWith(fileName); - ++i; - } - return valid; - } - - private void performValidation(IFile f, IReporter reporter, IStructuredModel model) { - if (!reporter.isCancelled()) - fJSPJavaValidator.performValidation(f, reporter, model); - if (!reporter.isCancelled()) - fJSPDirectiveValidator.performValidation(f, reporter, model.getStructuredDocument()); - if (!reporter.isCancelled()) - fJSPELValidator.performValidation(f, reporter, model.getStructuredDocument()); - if (!reporter.isCancelled()) - fJSPActionValidator.performValidation(f, reporter, model); - } - - /** - * @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement, - * java.lang.String, java.lang.Object) - */ - public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException { - fAdditionalContentTypesIDs = new String[0]; - if (data != null) { - if (data instanceof String && data.toString().length() > 0) { - fAdditionalContentTypesIDs = StringUtils.unpack(data.toString()); - } - } - } - - private boolean shouldValidate(IFile file) { - IResource resource = file; - do { - if (resource.isDerived() || resource.isTeamPrivateMember() || !resource.isAccessible() || resource.getName().charAt(0) == '.') { - return false; - } - resource = resource.getParent(); - } - while ((resource.getType() & IResource.PROJECT) == 0); - return true; - } - - public void validate(IValidationContext helper, IReporter reporter) throws ValidationException { - doValidate(helper, reporter); - } - - /** - * Validate one file. It's assumed that the file has JSP content type. - * - * @param f - * @param reporter - */ - void validateFile(IFile f, IReporter reporter) { - try { - f.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor()); - } - catch (CoreException e) { - Logger.logException(e); - } - IStructuredModel model = null; - try { - // get JSP model on behalf of all JSP validators - model = StructuredModelManager.getModelManager().getModelForRead(f); - if (!reporter.isCancelled() && model != null) { - reporter.removeAllMessages(this, f); - performValidation(f, reporter, model); - } - } - catch (IOException e) { - Logger.logException(e); - } - catch (CoreException e) { - Logger.logException(e); - } - finally { - if (model != null) - model.releaseFromRead(); - } - } - - public IStatus validateInJob(final IValidationContext helper, final IReporter reporter) throws ValidationException { - Job currentJob = Job.getJobManager().currentJob(); - ISchedulingRule rule = null; - if (currentJob != null) { - rule = currentJob.getRule(); - } - IWorkspaceRunnable validationRunnable = new IWorkspaceRunnable() { - public void run(IProgressMonitor monitor) throws CoreException { - try { - doValidate(helper, reporter); - } - catch (ValidationException e) { - throw new CoreException(new Status(IStatus.ERROR, PLUGIN_ID_JSP_CORE, 0, PLUGIN_ID_JSP_CORE, e)); - } - } - }; - try { - JavaCore.run(validationRunnable, rule, new NullProgressMonitor()); - } - catch (CoreException e) { - if (e.getCause() instanceof ValidationException) { - throw (ValidationException) e.getCause(); - } - throw new ValidationException(new LocalizedMessage(IMessage.ERROR_AND_WARNING, e.getMessage()), e); - } - return Status.OK_STATUS; - } - - public ValidationResult validate(final IResource resource, int kind, ValidationState state, IProgressMonitor monitor) { - if (resource.getType() != IResource.FILE) - return null; - final ValidationResult result = new ValidationResult(); - final IReporter reporter = result.getReporter(monitor); - - if(result.getDependsOn() != null) { - fDependsOn = new HashSet(Arrays.asList(result.getDependsOn())); - } - else { - fDependsOn = new HashSet(); - } - - // add web.xml as a dependency - addDependsOn(DeploymentDescriptorPropertyCache.getInstance().getWebXML(resource.getFullPath())); - - // List relevant JSP 2.0 preludes/codas as dependencies - IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); - PropertyGroup[] propertyGroups = DeploymentDescriptorPropertyCache.getInstance().getPropertyGroups(resource.getFullPath()); - for (int j = 0; j < propertyGroups.length; j++) { - IPath[] preludes = propertyGroups[j].getIncludePrelude(); - for (int i = 0; i < preludes.length; i++) { - addDependsOn(workspaceRoot.getFile(preludes[i])); - } - IPath[] codas = propertyGroups[j].getIncludeCoda(); - for (int i = 0; i < codas.length; i++) { - addDependsOn(workspaceRoot.getFile(codas[i])); - } - } - - IWorkspaceRunnable validationRunnable = new IWorkspaceRunnable() { - public void run(IProgressMonitor monitor) throws CoreException { - if (fragmentCheck((IFile) resource)) { - validateFile((IFile) resource, reporter); - } - IResource[] resources = (IResource[]) fDependsOn.toArray(new IResource[fDependsOn.size()]); - result.setDependsOn(resources); - fDependsOn.clear(); - } - }; - Job currentJob = Job.getJobManager().currentJob(); - ISchedulingRule rule = null; - if (currentJob != null) { - rule = currentJob.getRule(); - } - try { - JavaCore.run(validationRunnable, rule, new NullProgressMonitor()); - } - catch (CoreException e) { - Logger.logException(e); - } - return result; - } -} diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPContentValidator.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPContentValidator.java deleted file mode 100644 index 2c13d19fb2..0000000000 --- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPContentValidator.java +++ /dev/null @@ -1,265 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.jsp.core.internal.validation; - -import java.io.IOException; -import java.io.InputStream; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.jst.jsp.core.internal.Logger; -import org.eclipse.jst.jsp.core.internal.provisional.contenttype.ContentTypeIdForJSP; -import org.eclipse.wst.html.core.internal.document.HTMLDocumentTypeConstants; -import org.eclipse.wst.html.core.internal.validate.HTMLValidationAdapterFactory; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.INodeAdapterFactory; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.validate.ValidationAdapter; -import org.eclipse.wst.validation.ValidationResult; -import org.eclipse.wst.validation.ValidationState; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.xml.core.internal.document.DocumentTypeAdapter; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel; -import org.eclipse.wst.xml.core.internal.validation.eclipse.Validator; -import org.w3c.dom.Element; - -/** - * This validator validates the contents of the content type of the JSP, like - * the HTML regions in a JSP with content type="text/html" - */ -public class JSPContentValidator extends JSPValidator { - private static final String HTTP_JAVA_SUN_COM_JSP_PAGE = "http://java.sun.com/JSP/Page"; //$NON-NLS-1$ - private static final String XMLNS = "xmlns"; //$NON-NLS-1$ - private static final String XMLNS_JSP = "xmlns:jsp"; //$NON-NLS-1$ - private IContentType fJSPFContentType = null; - - - /** - * Checks if file is a jsp fragment or not. If so, check if the fragment - * should be validated or not. - * - * @param file - * Assumes shouldValidate was already called on file so it - * should not be null and does exist - * @return false if file is a fragment and it should not be validated, - * true otherwise - */ - private boolean fragmentCheck(IFile file) { - boolean shouldValidate = true; - // quick check to see if this is possibly a jsp fragment - if (getJSPFContentType().isAssociatedWith(file.getName())) { - // get preference for validate jsp fragments - boolean shouldValidateFragments = FragmentValidationTools.shouldValidateFragment(file); - /* - * if jsp fragments should not be validated, check if file is - * really jsp fragment - */ - if (!shouldValidateFragments) { - boolean isFragment = isFragment(file); - shouldValidate = !isFragment; - } - } - return shouldValidate; - } - - /** - * Returns JSP fragment content type - * - * @return jspf content type - */ - private IContentType getJSPFContentType() { - if (fJSPFContentType == null) { - fJSPFContentType = Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT); - } - return fJSPFContentType; - } - - /* - * Copied from HTMLValidator - */ - private HTMLValidationReporter getReporter(IReporter reporter, IFile file, IDOMModel model) { - return new HTMLValidationReporter(this, reporter, file, model); - } - - /* - * Copied from HTMLValidator - */ - private boolean hasHTMLFeature(IDOMDocument document) { - DocumentTypeAdapter adapter = (DocumentTypeAdapter) document.getAdapterFor(DocumentTypeAdapter.class); - if (adapter == null) - return false; - return adapter.hasFeature(HTMLDocumentTypeConstants.HTML); - } - - /** - * Determines if file is jsp fragment or not (does a deep, indepth check, - * looking into contents of file) - * - * @param file - * assumes file is not null and exists - * @return true if file is jsp fragment, false otherwise - */ - private boolean isFragment(IFile file) { - boolean isFragment = false; - InputStream is = null; - try { - IContentDescription contentDescription = file.getContentDescription(); - // it can be null - if (contentDescription == null) { - is = file.getContents(); - contentDescription = Platform.getContentTypeManager().getDescriptionFor(is, file.getName(), new QualifiedName[]{IContentDescription.CHARSET}); - } - if (contentDescription != null) { - String fileCtId = contentDescription.getContentType().getId(); - isFragment = (fileCtId != null && ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT.equals(fileCtId)); - } - } - catch (IOException e) { - // ignore, assume it's invalid JSP - } - catch (CoreException e) { - // ignore, assume it's invalid JSP - } - finally { - /* - * must close input stream in case others need it - * (IFile.getContents() requirement as well) - */ - if (is != null) - try { - is.close(); - } - catch (Exception e) { - // not sure how to recover at this point - } - } - return isFragment; - } - - private boolean isXMLJSP(IDOMDocument document) { - Element root = document.getDocumentElement(); - return root != null && (root.hasAttribute(XMLNS_JSP) || HTTP_JAVA_SUN_COM_JSP_PAGE.equals(root.getAttribute(XMLNS))); - } - - private void validate(IFile file, int kind, ValidationState state, IProgressMonitor monitor, IDOMModel model, IReporter reporter) { - IDOMDocument document = model.getDocument(); - if (document == null) - return; // error - - boolean isXMLJSP = isXMLJSP(document); - boolean hasHTMLFeature = hasHTMLFeature(document); - - if (hasHTMLFeature && !isXMLJSP) { - INodeAdapterFactory factory = HTMLValidationAdapterFactory.getInstance(); - ValidationAdapter adapter = (ValidationAdapter) factory.adapt(document); - if (adapter != null) { - HTMLValidationReporter rep = getReporter(reporter, file, model); - rep.clear(); - adapter.setReporter(rep); - adapter.validate(document); - } - } - if (!hasHTMLFeature && isXMLJSP) { - Validator xmlValidator = new Validator(); - xmlValidator.validate(file, kind, state, monitor); - } - } - - - /* - * Mostly copied from HTMLValidator - */ - private void validate(IReporter reporter, IFile file, IDOMModel model) { - if (file == null || model == null) - return; // error - IDOMDocument document = model.getDocument(); - if (document == null) - return; // error - - // This validator currently only handles validating HTML content in - // JSP - boolean hasXMLFeature = isXMLJSP(document); - boolean hasHTMLFeature = hasHTMLFeature(document); - if (hasHTMLFeature && !hasXMLFeature) { - INodeAdapterFactory factory = HTMLValidationAdapterFactory.getInstance(); - ValidationAdapter adapter = (ValidationAdapter) factory.adapt(document); - if (adapter == null) - return; // error - - HTMLValidationReporter rep = getReporter(reporter, file, model); - rep.clear(); - adapter.setReporter(rep); - adapter.validate(document); - } - } - - public ValidationResult validate(final IResource resource, int kind, ValidationState state, IProgressMonitor monitor) { - if (resource.getType() != IResource.FILE) - return null; - - ValidationResult result = new ValidationResult(); - final IReporter reporter = result.getReporter(monitor); - - if (fragmentCheck((IFile) resource)) { - IStructuredModel model = null; - try { - model = StructuredModelManager.getModelManager().getModelForRead((IFile) resource); - if (!reporter.isCancelled() && model instanceof IDOMModel) { - reporter.removeAllMessages(this, resource); - validate((IFile) resource, kind, state, monitor, (IDOMModel) model, reporter); - } - } - catch (IOException e) { - Logger.logException(e); - } - catch (CoreException e) { - Logger.logException(e); - } - finally { - if (model != null) - model.releaseFromRead(); - } - } - - return result; - } - - protected void validateFile(IFile f, IReporter reporter) { - IStructuredModel model = null; - try { - if (fragmentCheck(f)) { - model = StructuredModelManager.getModelManager().getModelForRead(f); - if (!reporter.isCancelled() && model instanceof IDOMModel) { - reporter.removeAllMessages(this, f); - validate(reporter, f, (IDOMModel) model); - } - } - } - catch (IOException e) { - Logger.logException(e); - } - catch (CoreException e) { - Logger.logException(e); - } - finally { - if (model != null) - model.releaseFromRead(); - } - } - -} diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPDirectiveValidator.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPDirectiveValidator.java deleted file mode 100644 index 2be056369f..0000000000 --- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPDirectiveValidator.java +++ /dev/null @@ -1,711 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.jst.jsp.core.internal.validation; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceVisitor; -import org.eclipse.core.resources.ProjectScope; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.preferences.DefaultScope; -import org.eclipse.core.runtime.preferences.IEclipsePreferences; -import org.eclipse.core.runtime.preferences.IPreferencesService; -import org.eclipse.core.runtime.preferences.IScopeContext; -import org.eclipse.core.runtime.preferences.InstanceScope; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jst.jsp.core.internal.JSPCoreMessages; -import org.eclipse.jst.jsp.core.internal.JSPCorePlugin; -import org.eclipse.jst.jsp.core.internal.Logger; -import org.eclipse.jst.jsp.core.internal.contenttype.DeploymentDescriptorPropertyCache; -import org.eclipse.jst.jsp.core.internal.preferences.JSPCorePreferenceNames; -import org.eclipse.jst.jsp.core.internal.provisional.JSP11Namespace; -import org.eclipse.jst.jsp.core.internal.regions.DOMJSPRegionContexts; -import org.eclipse.jst.jsp.core.internal.util.FacetModuleCoreSupport; -import org.eclipse.jst.jsp.core.taglib.IJarRecord; -import org.eclipse.jst.jsp.core.taglib.ITLDRecord; -import org.eclipse.jst.jsp.core.taglib.ITagDirRecord; -import org.eclipse.jst.jsp.core.taglib.ITaglibRecord; -import org.eclipse.jst.jsp.core.taglib.IURLRecord; -import org.eclipse.jst.jsp.core.taglib.TaglibIndex; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.html.core.internal.contentmodel.JSP20Namespace; -import org.eclipse.wst.html.core.internal.preferences.HTMLCorePreferenceNames; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionContainer; -import org.eclipse.wst.sse.core.internal.text.IRegionComparible; -import org.eclipse.wst.sse.core.internal.validate.ValidationMessage; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; - -import com.ibm.icu.text.Collator; - -/** - * Checks for: - duplicate taglib prefix values and reserved taglib prefix - * values in the same file - */ -public class JSPDirectiveValidator extends JSPValidator { - /** - * - */ - private static final String PREFERENCE_NODE_QUALIFIER = JSPCorePlugin.getDefault().getBundle().getSymbolicName(); - - private static Collator collator = Collator.getInstance(Locale.US); - - private static final boolean DEBUG = Boolean.valueOf(Platform.getDebugOption("org.eclipse.jst.jsp.core/debug/jspvalidator")).booleanValue(); //$NON-NLS-1$ - - private IValidator fMessageOriginator; - private IEclipsePreferences fPreferences = null; - - private IPreferencesService fPreferencesService = null; - private HashMap fPrefixValueRegionToDocumentRegionMap = new HashMap(); - private IJavaProject fProject = null; - private HashMap fReservedPrefixes = new HashMap(); - private IScopeContext[] fScopes = null; - private int fSeverityIncludeFileMissing = -1; - private int fSeverityIncludeFileNotSpecified = -1; - private int fSeveritySuperClassNotFound = -1; - private int fSeverityTagdirUnresolvableURI = -1; - private int fSeverityTaglibDuplicatePrefixWithDifferentURIs = -1; - - private int fSeverityTaglibDuplicatePrefixWithSameURIs = -1; - private int fSeverityTaglibMissingPrefix = -1; - - private int fSeverityTaglibMissingURI = -1; - - - private int fSeverityTaglibUnresolvableURI = -1; - - private HashMap fTaglibPrefixesInUse = new HashMap(); - - public JSPDirectiveValidator() { - initReservedPrefixes(); - fMessageOriginator = this; - } - - public JSPDirectiveValidator(IValidator validator) { - initReservedPrefixes(); - this.fMessageOriginator = validator; - } - - /** - * Record that the currently validating resource depends on the given - * file. Only possible during batch (not source) validation. - * - * @param file - */ - private void addDependsOn(IResource file) { - if (fMessageOriginator instanceof JSPBatchValidator) { - ((JSPBatchValidator) fMessageOriginator).addDependsOn(file); - } - } - - public void cleanup(IReporter reporter) { - super.cleanup(reporter); - fTaglibPrefixesInUse.clear(); - fPrefixValueRegionToDocumentRegionMap.clear(); - } - - private void collectTaglibPrefix(IStructuredDocumentRegion documentRegion, ITextRegion valueRegion, String taglibPrefix) { - fPrefixValueRegionToDocumentRegionMap.put(valueRegion, documentRegion); - - Object o = fTaglibPrefixesInUse.get(taglibPrefix); - if (o == null) { - // prefix doesn't exist, remember it - fTaglibPrefixesInUse.put(taglibPrefix, valueRegion); - } - else { - List regionList = null; - // already a List - if (o instanceof List) { - regionList = (List) o; - } - /* - * a single value region, create a new List and add previous - * valueRegion - */ - else { - regionList = new ArrayList(); - regionList.add(o); - fTaglibPrefixesInUse.put(taglibPrefix, regionList); - } - regionList.add(valueRegion); - } - } - - int getMessageSeverity(String key) { - int sev = fPreferencesService.getInt(PREFERENCE_NODE_QUALIFIER, key, IMessage.NORMAL_SEVERITY, fScopes); - switch (sev) { - case ValidationMessage.ERROR : - return IMessage.HIGH_SEVERITY; - case ValidationMessage.WARNING : - return IMessage.NORMAL_SEVERITY; - case ValidationMessage.INFORMATION : - return IMessage.LOW_SEVERITY; - case ValidationMessage.IGNORE : - return ValidationMessage.IGNORE; - } - return IMessage.NORMAL_SEVERITY; - } - private void initReservedPrefixes() { - fReservedPrefixes.put("jsp", ""); //$NON-NLS-1$ //$NON-NLS-2$ - fReservedPrefixes.put("jspx", ""); //$NON-NLS-1$ //$NON-NLS-2$ - fReservedPrefixes.put("java", ""); //$NON-NLS-1$ //$NON-NLS-2$ - fReservedPrefixes.put("javax", ""); //$NON-NLS-1$ //$NON-NLS-2$ - fReservedPrefixes.put("servlet", ""); //$NON-NLS-1$ //$NON-NLS-2$ - fReservedPrefixes.put("sun", ""); //$NON-NLS-1$ //$NON-NLS-2$ - fReservedPrefixes.put("sunw", ""); //$NON-NLS-1$ //$NON-NLS-2$ - } - - private boolean isReservedTaglibPrefix(String name) { - return fReservedPrefixes.get(name) != null; - } - - private void loadPreferences(IFile file) { - fScopes = new IScopeContext[]{new InstanceScope(), new DefaultScope()}; - - fPreferencesService = Platform.getPreferencesService(); - if (file != null && file.isAccessible()) { - ProjectScope projectScope = new ProjectScope(file.getProject()); - if (projectScope.getNode(PREFERENCE_NODE_QUALIFIER).getBoolean(JSPCorePreferenceNames.VALIDATION_USE_PROJECT_SETTINGS, false)) { - fScopes = new IScopeContext[]{projectScope, new InstanceScope(), new DefaultScope()}; - } - } - - fSeverityIncludeFileMissing = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_DIRECTIVE_INCLUDE_FILE_NOT_FOUND); - fSeverityIncludeFileNotSpecified = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_DIRECTIVE_INCLUDE_NO_FILE_SPECIFIED); - fSeverityTaglibDuplicatePrefixWithDifferentURIs = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_DIRECTIVE_TAGLIB_DUPLICATE_PREFIXES_DIFFERENT_URIS); - fSeverityTaglibDuplicatePrefixWithSameURIs = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_DIRECTIVE_TAGLIB_DUPLICATE_PREFIXES_SAME_URIS); - fSeverityTaglibMissingPrefix = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_DIRECTIVE_TAGLIB_MISSING_PREFIX); - fSeverityTaglibMissingURI = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_DIRECTIVE_TAGLIB_MISSING_URI_OR_TAGDIR); - fSeverityTaglibUnresolvableURI = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_DIRECTIVE_TAGLIB_UNRESOLVABLE_URI_OR_TAGDIR); - fSeverityTagdirUnresolvableURI = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_DIRECTIVE_TAGLIB_UNRESOLVABLE_URI_OR_TAGDIR); - fSeveritySuperClassNotFound = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_DIRECTIVE_PAGE_SUPERCLASS_NOT_FOUND); - - } - - protected void performValidation(IFile f, IReporter reporter, IStructuredDocument sDoc) { - loadPreferences(f); - - - setProject(f.getProject()); - /* - * when validating an entire file need to clear dupes or else you're - * comparing between files - */ - fPrefixValueRegionToDocumentRegionMap.clear(); - fTaglibPrefixesInUse.clear(); - - IRegionComparible comparer = null; - if (sDoc instanceof IRegionComparible) - comparer = (IRegionComparible) sDoc; - - // iterate all document regions - IStructuredDocumentRegion region = sDoc.getFirstStructuredDocumentRegion(); - while (region != null && !reporter.isCancelled()) { - // only checking directives - if (region.getType() == DOMJSPRegionContexts.JSP_DIRECTIVE_NAME) { - processDirective(reporter, f, sDoc, region); - } - // requires tag name, attribute, equals, and value - else if (comparer != null && region.getNumberOfRegions() > 4) { - ITextRegion nameRegion = region.getRegions().get(1); - if (comparer.regionMatches(region.getStartOffset(nameRegion), nameRegion.getTextLength(), "jsp:include")) { - processIncludeDirective(reporter, f, sDoc, region); - } - - } - region = region.getNext(); - } - - if (!reporter.isCancelled()) { - reportTaglibDuplicatePrefixes(f, reporter, sDoc); - } - - fPrefixValueRegionToDocumentRegionMap.clear(); - fTaglibPrefixesInUse.clear(); - setProject(null); - unloadPreferences(); - } - - private void processDirective(IReporter reporter, IFile file, IStructuredDocument sDoc, IStructuredDocumentRegion documentRegion) { - String directiveName = getDirectiveName(documentRegion); - // we only care about taglib directive - if (directiveName.equals("taglib")) { //$NON-NLS-1$ - processTaglibDirective(reporter, file, sDoc, documentRegion); - } - else if (directiveName.equals("include")||directiveName.equals("jsp:include")) { //$NON-NLS-1$ //$NON-NLS-2$ - processIncludeDirective(reporter, file, sDoc, documentRegion); - } - else if (directiveName.equals("page")) { //$NON-NLS-1$ - processPageDirective(reporter, file, sDoc, documentRegion); - } - } - - private void processIncludeDirective(IReporter reporter, IFile file, IStructuredDocument sDoc, IStructuredDocumentRegion documentRegion) { - ITextRegion fileValueRegion = getAttributeValueRegion(documentRegion, JSP11Namespace.ATTR_NAME_FILE); - if (fileValueRegion == null) - fileValueRegion = getAttributeValueRegion(documentRegion, JSP11Namespace.ATTR_NAME_PAGE); - // There is a file and it isn't a nested region which could contain a JSP expression - if (fileValueRegion != null && !hasNestedRegion(fileValueRegion)) { - // file specified - String fileValue = documentRegion.getText(fileValueRegion); - fileValue = StringUtils.stripQuotes(fileValue); - - if (fileValue.length() == 0 && fSeverityIncludeFileNotSpecified != ValidationMessage.IGNORE) { - // file value is specified but empty - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_3, JSP11Namespace.ATTR_NAME_FILE); - LocalizedMessage message = new LocalizedMessage(fSeverityIncludeFileNotSpecified, msgText, file); - int start = documentRegion.getStartOffset(fileValueRegion); - int length = fileValueRegion.getTextLength(); - int lineNo = sDoc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - else if (DeploymentDescriptorPropertyCache.getInstance().getURLMapping(file.getFullPath(), fileValue) == null) { - IPath testPath = FacetModuleCoreSupport.resolve(file.getFullPath(), fileValue); - if (testPath.segmentCount() > 1) { - IFile testFile = file.getWorkspace().getRoot().getFile(testPath); - addDependsOn(testFile); - if (!testFile.isAccessible()) { - if (fSeverityIncludeFileMissing != ValidationMessage.IGNORE) { - // File not found - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_4, new String[]{fileValue, testPath.toString()}); - LocalizedMessage message = new LocalizedMessage(fSeverityIncludeFileMissing, msgText, file); - int start = documentRegion.getStartOffset(fileValueRegion); - int length = fileValueRegion.getTextLength(); - int lineNo = sDoc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - } - } - } - } - else if (fileValueRegion == null && fSeverityIncludeFileNotSpecified != ValidationMessage.IGNORE) { - // file is not specified at all - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_3, JSP11Namespace.ATTR_NAME_FILE); - LocalizedMessage message = new LocalizedMessage(fSeverityIncludeFileNotSpecified, msgText, file); - int start = documentRegion.getStartOffset(); - int length = documentRegion.getTextLength(); - int lineNo = sDoc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - } - - /** - * @param reporter - * @param file - * @param doc - * @param documentRegion - */ - private void processPageDirective(IReporter reporter, IFile file, IStructuredDocument doc, IStructuredDocumentRegion documentRegion) { - ITextRegion superclassValueRegion = getAttributeValueRegion(documentRegion, JSP11Namespace.ATTR_NAME_EXTENDS); - if (superclassValueRegion != null) { - // file specified - String superclassName = documentRegion.getText(superclassValueRegion); - superclassName = StringUtils.stripQuotes(superclassName); - - IType superClass = null; - if (superclassName != null && superclassName.length() > 0 && fProject != null && fProject.exists()) { - try { - superClass = fProject.findType(superclassName.trim(), new NullProgressMonitor()); - } - catch (JavaModelException e) { - Logger.logException(e); - } - } - - if (superClass == null && fSeveritySuperClassNotFound != ValidationMessage.IGNORE) { - // superclass not found - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_8, superclassName); - LocalizedMessage message = new LocalizedMessage(fSeveritySuperClassNotFound, msgText, file); - int start = documentRegion.getStartOffset(superclassValueRegion); - int length = superclassValueRegion.getTextLength(); - int lineNo = doc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - } - } - - private void processTaglibDirective(IReporter reporter, IFile file, IStructuredDocument sDoc, IStructuredDocumentRegion documentRegion) { - ITextRegion prefixValueRegion = null; - ITextRegion uriValueRegion = getAttributeValueRegion(documentRegion, JSP11Namespace.ATTR_NAME_URI); - ITextRegion tagdirValueRegion = getAttributeValueRegion(documentRegion, JSP20Namespace.ATTR_NAME_TAGDIR); - if (uriValueRegion != null) { - // URI is specified - String uri = documentRegion.getText(uriValueRegion); - - if (file != null) { - uri = StringUtils.stripQuotes(uri); - if (uri.length() > 0) { - ITaglibRecord reference = TaglibIndex.resolve(file.getFullPath().toString(), uri, false); - if (reference != null) { - switch (reference.getRecordType()) { - case (ITaglibRecord.TLD) : { - ITLDRecord record = (ITLDRecord) reference; - IResource tldfile = ResourcesPlugin.getWorkspace().getRoot().getFile(record.getPath()); - addDependsOn(tldfile); - } - break; - case (ITaglibRecord.JAR) : { - IJarRecord record = (IJarRecord) reference; - IFile[] foundFilesForLocation = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(record.getLocation()); - for (int i = 0; i < foundFilesForLocation.length; i++) { - addDependsOn(foundFilesForLocation[i]); - } - } - break; - case (ITaglibRecord.TAGDIR) : { - ITagDirRecord record = (ITagDirRecord) reference; - IPath path = record.getPath(); - IResource found = ResourcesPlugin.getWorkspace().getRoot().findMember(path, false); - - try { - found.accept(new IResourceVisitor() { - public boolean visit(IResource resource) throws CoreException { - if (resource.getType() == IResource.FILE) { - addDependsOn(resource); - } - return true; - } - }); - } - catch (CoreException e) { - Logger.logException(e); - } - } - break; - case (ITaglibRecord.URL) : { - IURLRecord record = (IURLRecord) reference; - String baseLocation = record.getBaseLocation(); - if (baseLocation != null && baseLocation.indexOf("://") < 0) { - IResource found = ResourcesPlugin.getWorkspace().getRoot().findMember(baseLocation, false); - if (found != null) { - try { - found.accept(new IResourceVisitor() { - public boolean visit(IResource resource) throws CoreException { - if (resource.getType() == IResource.FILE) { - addDependsOn(resource); - } - return true; - } - }); - } - catch (CoreException e) { - Logger.logException(e); - } - } - else { - IFile externalJar = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new Path(baseLocation)); - if (externalJar != null) { - addDependsOn(externalJar); - } - } - } - } - break; - } - } - if (reference == null && fSeverityTaglibUnresolvableURI != ValidationMessage.IGNORE) { - // URI specified but does not resolve - String msgText = null; - // provide better messages for typical "http:*" URIs - if (uri.startsWith("http:") && DeploymentDescriptorPropertyCache.getInstance().getJSPVersion(file.getFullPath()) < 1.2) { //$NON-NLS-1$ - if (FacetModuleCoreSupport.isDynamicWebProject(file.getProject())) { - msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_9, uri); - } - else { - msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_10, uri); - } - } - else { - msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_1, uri); - } - LocalizedMessage message = new LocalizedMessage(fSeverityTaglibUnresolvableURI, msgText, file); - int start = documentRegion.getStartOffset(uriValueRegion); - int length = uriValueRegion.getTextLength(); - int lineNo = sDoc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - message.setAttribute("PROBLEM_ID", new Integer(611)); //$NON-NLS-1$ - - reporter.addMessage(fMessageOriginator, message); - } - } - else if (fSeverityTaglibMissingURI != ValidationMessage.IGNORE) { - // URI specified but empty string - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_3, JSP11Namespace.ATTR_NAME_URI); - LocalizedMessage message = new LocalizedMessage(fSeverityTaglibMissingURI, msgText, file); - int start = documentRegion.getStartOffset(uriValueRegion); - int length = uriValueRegion.getTextLength(); - int lineNo = sDoc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - } - } - else if (tagdirValueRegion != null) { - // URI is specified - String tagdir = documentRegion.getText(tagdirValueRegion); - - if (file != null) { - tagdir = StringUtils.stripQuotes(tagdir); - if (tagdir.length() <= 0 && fSeverityTaglibMissingURI != ValidationMessage.IGNORE) { - // tagdir specified but empty string - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_3, JSP20Namespace.ATTR_NAME_TAGDIR); - LocalizedMessage message = new LocalizedMessage(fSeverityTaglibMissingURI, msgText, file); - int start = documentRegion.getStartOffset(tagdirValueRegion); - int length = tagdirValueRegion.getTextLength(); - int lineNo = sDoc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - else if (TaglibIndex.resolve(file.getFullPath().toString(), tagdir, false) == null && fSeverityTagdirUnresolvableURI != ValidationMessage.IGNORE) { - // URI specified but does not resolve - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_11, tagdir); - LocalizedMessage message = new LocalizedMessage(fSeverityTaglibUnresolvableURI, msgText, file); - int start = documentRegion.getStartOffset(tagdirValueRegion); - int length = tagdirValueRegion.getTextLength(); - int lineNo = sDoc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - } - } - else if (fSeverityTaglibMissingURI != ValidationMessage.IGNORE) { - // URI not specified or empty string - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_7, new String[]{JSP20Namespace.ATTR_NAME_TAGDIR, JSP11Namespace.ATTR_NAME_URI}); - LocalizedMessage message = new LocalizedMessage(fSeverityTaglibMissingURI, msgText, file); - int start = documentRegion.getStartOffset(); - int length = documentRegion.getTextLength(); - int lineNo = sDoc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - - prefixValueRegion = getAttributeValueRegion(documentRegion, JSP11Namespace.ATTR_NAME_PREFIX); - if (prefixValueRegion != null) { - // prefix specified - String taglibPrefix = documentRegion.getText(prefixValueRegion); - taglibPrefix = StringUtils.stripQuotes(taglibPrefix); - - collectTaglibPrefix(documentRegion, prefixValueRegion, taglibPrefix); - - if (isReservedTaglibPrefix(taglibPrefix)) { - // prefix is a reserved prefix - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_0, taglibPrefix); - int sev = IMessage.HIGH_SEVERITY; - LocalizedMessage message = (file == null ? new LocalizedMessage(sev, msgText) : new LocalizedMessage(sev, msgText, file)); - int start = documentRegion.getStartOffset(prefixValueRegion); - int length = prefixValueRegion.getTextLength(); - int lineNo = sDoc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - if (taglibPrefix.length() == 0 && fSeverityTaglibMissingPrefix != ValidationMessage.IGNORE) { - // prefix is specified but empty - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_3, JSP11Namespace.ATTR_NAME_PREFIX); - LocalizedMessage message = new LocalizedMessage(fSeverityTaglibMissingPrefix, msgText, file); - int start = documentRegion.getStartOffset(prefixValueRegion); - int length = prefixValueRegion.getTextLength(); - int lineNo = sDoc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - } - else if (fSeverityTaglibMissingPrefix != ValidationMessage.IGNORE) { - // prefix is not specified - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_3, JSP11Namespace.ATTR_NAME_PREFIX); - LocalizedMessage message = new LocalizedMessage(fSeverityTaglibMissingPrefix, msgText, file); - int start = documentRegion.getStartOffset(); - int length = documentRegion.getTextLength(); - int lineNo = sDoc.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - } - - private void reportTaglibDuplicatePrefixes(IFile file, IReporter reporter, IStructuredDocument document) { - if (fSeverityTaglibDuplicatePrefixWithDifferentURIs == ValidationMessage.IGNORE && fSeverityTaglibDuplicatePrefixWithSameURIs == ValidationMessage.IGNORE) - return; - - String[] prefixes = (String[]) fTaglibPrefixesInUse.keySet().toArray(new String[0]); - for (int prefixNumber = 0; prefixNumber < prefixes.length; prefixNumber++) { - int severity = fSeverityTaglibDuplicatePrefixWithSameURIs; - - Object o = fTaglibPrefixesInUse.get(prefixes[prefixNumber]); - /* - * Only care if it's a List (because there was more than one - * directive with that prefix) and if we're supposed to report - * duplicates - */ - if (o instanceof List) { - List valueRegions = (List) o; - String uri = null; - for (int regionNumber = 0; regionNumber < valueRegions.size(); regionNumber++) { - IStructuredDocumentRegion documentRegion = (IStructuredDocumentRegion) fPrefixValueRegionToDocumentRegionMap.get(valueRegions.get(regionNumber)); - ITextRegion uriValueRegion = getAttributeValueRegion(documentRegion, JSP11Namespace.ATTR_NAME_URI); - if (uriValueRegion == null) { - uriValueRegion = getAttributeValueRegion(documentRegion, JSP20Namespace.ATTR_NAME_TAGDIR); - } - if (uriValueRegion != null) { - String uri2 = StringUtils.stripQuotes(documentRegion.getText(uriValueRegion)); - if (uri == null) { - uri = uri2; - } - else { - if (collator.compare(uri, uri2) != 0) { - severity = fSeverityTaglibDuplicatePrefixWithDifferentURIs; - } - } - } - } - - if (severity != ValidationMessage.IGNORE) { - String msgText = NLS.bind(JSPCoreMessages.JSPDirectiveValidator_2, prefixes[prefixNumber]); //$NON-NLS-2$ //$NON-NLS-1$ - - // Report an error in all directives using this prefix - for (int regionNumber = 0; regionNumber < valueRegions.size(); regionNumber++) { - - ITextRegion valueRegion = (ITextRegion) valueRegions.get(regionNumber); - IStructuredDocumentRegion documentRegion = (IStructuredDocumentRegion) fPrefixValueRegionToDocumentRegionMap.get(valueRegion); - LocalizedMessage message = (file == null ? new LocalizedMessage(severity, msgText) : new LocalizedMessage(severity, msgText, file)); - - // if there's a message, there was an error found - int start = documentRegion.getStartOffset(valueRegion); - int length = valueRegion.getTextLength(); - int lineNo = document.getLineOfOffset(start); - message.setLineNo(lineNo + 1); - message.setOffset(start); - message.setLength(length); - - reporter.addMessage(fMessageOriginator, message); - } - } - } - } - } - - /** - * @param project - */ - private void setProject(IProject project) { - boolean useProject = false; - if (project != null) { - fProject = JavaCore.create(project); - fPreferences = new ProjectScope(fProject.getProject()).getNode(PREFERENCE_NODE_QUALIFIER); - useProject = fPreferences.getBoolean(HTMLCorePreferenceNames.USE_PROJECT_SETTINGS, false); - } - else { - fProject = null; - } - - if (!useProject) { - fPreferences = new InstanceScope().getNode(PREFERENCE_NODE_QUALIFIER); - } - } - - private void unloadPreferences() { - fPreferencesService = null; - fScopes = null; - } - - /** - * True if container has nested regions, meaning container is probably too - * complicated (like JSP expressions or EL) to validate with this validator. - */ - private boolean hasNestedRegion(ITextRegion container) { - return (container instanceof ITextRegionContainer && ((ITextRegionContainer) container).getRegions() != null); - } - - /** - * batch validation call - */ - protected void validateFile(IFile f, IReporter reporter) { - if (DEBUG) { - Logger.log(Logger.INFO, getClass().getName() + " validating: " + f); //$NON-NLS-1$ - } - - IStructuredModel sModel = null; - try { - sModel = StructuredModelManager.getModelManager().getModelForRead(f); - if (sModel != null && !reporter.isCancelled()) { - performValidation(f, reporter, sModel.getStructuredDocument()); - } - } - catch (Exception e) { - Logger.logException(e); - } - finally { - if (sModel != null) - sModel.releaseFromRead(); - } - } -} diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPELValidator.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPELValidator.java deleted file mode 100644 index cf84532243..0000000000 --- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPELValidator.java +++ /dev/null @@ -1,222 +0,0 @@ -/******************************************************************************* - Copyright (c) 2005, 2008 BEA Systems and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * BEA Systems - initial implementation - * - *******************************************************************************/ -package org.eclipse.jst.jsp.core.internal.validation; - -import java.util.Iterator; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.ProjectScope; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.preferences.DefaultScope; -import org.eclipse.core.runtime.preferences.IPreferencesService; -import org.eclipse.core.runtime.preferences.IScopeContext; -import org.eclipse.core.runtime.preferences.InstanceScope; -import org.eclipse.jst.jsp.core.internal.JSPCoreMessages; -import org.eclipse.jst.jsp.core.internal.JSPCorePlugin; -import org.eclipse.jst.jsp.core.internal.Logger; -import org.eclipse.jst.jsp.core.internal.java.jspel.JSPELParser; -import org.eclipse.jst.jsp.core.internal.java.jspel.ParseException; -import org.eclipse.jst.jsp.core.internal.java.jspel.Token; -import org.eclipse.jst.jsp.core.internal.java.jspel.TokenMgrError; -import org.eclipse.jst.jsp.core.internal.preferences.JSPCorePreferenceNames; -import org.eclipse.jst.jsp.core.internal.regions.DOMJSPRegionContexts; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionCollection; -import org.eclipse.wst.sse.core.internal.validate.ValidationMessage; -import org.eclipse.wst.validation.internal.core.Message; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; -import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext; - - -public class JSPELValidator extends JSPValidator { - private static final boolean DEBUG = Boolean.valueOf(Platform.getDebugOption("org.eclipse.jst.jsp.core/debug/jspvalidator")).booleanValue(); //$NON-NLS-1$ - private static final String PREFERENCE_NODE_QUALIFIER = JSPCorePlugin.getDefault().getBundle().getSymbolicName(); - private static final int MAX_REGIONS = 1000; - - private IValidator fMessageOriginator; - - public JSPELValidator() { - this.fMessageOriginator = this; - } - - public JSPELValidator(IValidator validator) { - this.fMessageOriginator = validator; - } - - protected void validateFile(IFile file, IReporter reporter) { - if (DEBUG) { - Logger.log(Logger.INFO, getClass().getName() + " validating: " + file); //$NON-NLS-1$ - } - - IStructuredModel model = null; - try { - model = StructuredModelManager.getModelManager().getModelForRead(file); - if (!reporter.isCancelled() && model != null) { - performValidation(file, reporter, model.getStructuredDocument()); - } - } - catch (Exception e) { - Logger.logException(e); - } - finally { - if (null != model) - model.releaseFromRead(); - } - } - - private IPreferencesService fPreferencesService = null; - private IScopeContext[] fScopes = null; - - private void loadPreferences(IFile file) { - fScopes = new IScopeContext[]{new InstanceScope(), new DefaultScope()}; - - fPreferencesService = Platform.getPreferencesService(); - if (file != null && file.isAccessible()) { - ProjectScope projectScope = new ProjectScope(file.getProject()); - if (projectScope.getNode(PREFERENCE_NODE_QUALIFIER).getBoolean(JSPCorePreferenceNames.VALIDATION_USE_PROJECT_SETTINGS, false)) { - fScopes = new IScopeContext[]{projectScope, new InstanceScope(), new DefaultScope()}; - } - } - } - - int getMessageSeverity(String key) { - int sev = fPreferencesService.getInt(PREFERENCE_NODE_QUALIFIER, key, IMessage.NORMAL_SEVERITY, fScopes); - switch (sev) { - case ValidationMessage.ERROR : - return IMessage.HIGH_SEVERITY; - case ValidationMessage.WARNING : - return IMessage.NORMAL_SEVERITY; - case ValidationMessage.INFORMATION : - return IMessage.LOW_SEVERITY; - case ValidationMessage.IGNORE : - return ValidationMessage.IGNORE; - } - return IMessage.NORMAL_SEVERITY; - } - - private void unloadPreferences() { - fPreferencesService = null; - fScopes = null; - } - - protected void performValidation(IFile file, IReporter reporter, IStructuredDocument structuredDoc) { - loadPreferences(file); - IStructuredDocumentRegion curNode = structuredDoc.getFirstStructuredDocumentRegion(); - while (null != curNode && !reporter.isCancelled()) { - if (curNode.getType() != DOMRegionContext.XML_COMMENT_TEXT && curNode.getType() != DOMRegionContext.XML_CDATA_TEXT && curNode.getType() != DOMRegionContext.UNDEFINED) { - validateRegionContainer(curNode, reporter, file); - } - curNode = curNode.getNext(); - } - unloadPreferences(); - } - - protected void validateRegionContainer(ITextRegionCollection container, IReporter reporter, IFile file) { - ITextRegionCollection containerRegion = container; - Iterator regions = containerRegion.getRegions().iterator(); - ITextRegion region = null; - while (regions.hasNext() && !reporter.isCancelled()) { - region = (ITextRegion) regions.next(); - String type = region.getType(); - if (type != null && region instanceof ITextRegionCollection) { - ITextRegionCollection parentRegion = ((ITextRegionCollection) region); - Iterator childRegions = parentRegion.getRegions().iterator(); - while (childRegions.hasNext() && !reporter.isCancelled()) { - ITextRegion childRegion = (ITextRegion) childRegions.next(); - /* [136795] Validate everything in the EL container, not just JSP_EL_CONTENT */ - if (childRegion.getType() == DOMJSPRegionContexts.JSP_EL_OPEN) - validateELContent(parentRegion, childRegion, childRegions, reporter, file); - } - } - } - } - - protected void validateELContent(ITextRegionCollection container, ITextRegion elOpenRegion, Iterator elRegions, IReporter reporter, IFile file) { - int contentStart = elOpenRegion.getEnd(); - int contentDocStart = container.getEndOffset(elOpenRegion); - int contentLength = container.getLength(); - int regionCount = 0; - ITextRegion elRegion = null; - /* Find the EL closing region, otherwise the last region will be used to calculate the EL content text */ - while (elRegions != null && elRegions.hasNext() && (regionCount++ < MAX_REGIONS)) { - elRegion = (ITextRegion) elRegions.next(); - if (elRegion.getType() == DOMJSPRegionContexts.JSP_EL_CLOSE) - break; - } - - String elText = container.getFullText().substring(contentStart, (elRegion != null) ? elRegion.getStart() : (contentLength - 1)); - JSPELParser elParser = JSPELParser.createParser(elText); - try { - elParser.Expression(); - } - catch (ParseException e) { - int sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_EL_SYNTAX); - if (sev != ValidationMessage.IGNORE) { - Token curTok = e.currentToken; - int problemStartOffset = contentDocStart + curTok.beginColumn; - Message message = new LocalizedMessage(sev, JSPCoreMessages.JSPEL_Syntax); - message.setOffset(problemStartOffset); - message.setLength(curTok.endColumn - curTok.beginColumn + 1); - message.setTargetObject(file); - reporter.addMessage(fMessageOriginator, message); - } - } - catch (TokenMgrError te) { - int sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_EL_LEXER); - if (sev != ValidationMessage.IGNORE) { - Message message = new LocalizedMessage(IMessage.NORMAL_SEVERITY, JSPCoreMessages.JSPEL_Token); - message.setOffset(contentDocStart); - message.setLength(contentLength); - message.setTargetObject(file); - reporter.addMessage(fMessageOriginator, message); - } - } - } - - protected void validateXMLNode(ITextRegionCollection container, ITextRegion region, IReporter reporter, IFile file) { - String elText = container.getText(region); - JSPELParser elParser = JSPELParser.createParser(elText); - int contentStart = container.getStartOffset(region); - int contentLength = container.getLength(); - try { - elParser.Expression(); - } - catch (ParseException e) { - int sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_EL_SYNTAX); - if (sev != ValidationMessage.IGNORE) { - Token curTok = e.currentToken; - int problemStartOffset = contentStart + curTok.beginColumn; - Message message = new LocalizedMessage(sev, JSPCoreMessages.JSPEL_Syntax); - message.setOffset(problemStartOffset); - message.setLength(curTok.endColumn - curTok.beginColumn + 1); - message.setTargetObject(file); - reporter.addMessage(fMessageOriginator, message); - } - } - catch (TokenMgrError te) { - int sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_EL_LEXER); - if (sev != ValidationMessage.IGNORE) { - Message message = new LocalizedMessage(IMessage.NORMAL_SEVERITY, JSPCoreMessages.JSPEL_Token); - message.setOffset(contentStart); - message.setLength(contentLength); - message.setTargetObject(file); - reporter.addMessage(fMessageOriginator, message); - } - } - } -} diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPJavaValidator.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPJavaValidator.java deleted file mode 100644 index d8ffbffb30..0000000000 --- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPJavaValidator.java +++ /dev/null @@ -1,434 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2010 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.jst.jsp.core.internal.validation; - -import java.io.IOException; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.ProjectScope; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.preferences.DefaultScope; -import org.eclipse.core.runtime.preferences.IPreferencesService; -import org.eclipse.core.runtime.preferences.IScopeContext; -import org.eclipse.core.runtime.preferences.InstanceScope; -import org.eclipse.jdt.core.compiler.IProblem; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.Position; -import org.eclipse.jst.jsp.core.internal.JSPCorePlugin; -import org.eclipse.jst.jsp.core.internal.Logger; -import org.eclipse.jst.jsp.core.internal.java.IJSPProblem; -import org.eclipse.jst.jsp.core.internal.java.IJSPTranslation; -import org.eclipse.jst.jsp.core.internal.java.JSPTranslation; -import org.eclipse.jst.jsp.core.internal.java.JSPTranslationAdapter; -import org.eclipse.jst.jsp.core.internal.java.JSPTranslationExtension; -import org.eclipse.jst.jsp.core.internal.modelhandler.ModelHandlerForJSP; -import org.eclipse.jst.jsp.core.internal.preferences.JSPCorePreferenceNames; -import org.eclipse.jst.jsp.core.internal.regions.DOMJSPRegionContexts; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.validate.ValidationMessage; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel; - -public class JSPJavaValidator extends JSPValidator { - private static final boolean DEBUG = Boolean.valueOf(Platform.getDebugOption("org.eclipse.jst.jsp.core/debug/jspvalidator")).booleanValue(); //$NON-NLS-1$ - private IValidator fMessageOriginator; - - private IPreferencesService fPreferencesService = Platform.getPreferencesService(); - private static final String PREFERENCE_NODE_QUALIFIER = JSPCorePlugin.getDefault().getBundle().getSymbolicName(); - private IScopeContext[] fScopes = null; - - private static final boolean UPDATE_JAVA_TASKS = true; - private static final String JAVA_TASK_MARKER_TYPE = "org.eclipse.jdt.core.task"; //$NON-NLS-1$ - private static final String[] DEPEND_ONs = new String[]{".classpath", ".project", ".settings/org.eclipse.jdt.core.prefs", ".settings/org.eclipse.jst.jsp.core.prefs", ".settings/org.eclipse.wst.common.project.facet.core.xml", ".settings/org.eclipse.wst.common.component"}; - - public JSPJavaValidator() { - this.fMessageOriginator = this; - } - - public JSPJavaValidator(IValidator validator) { - this.fMessageOriginator = validator; - } - - /** - * Assumed the message offset is an indirect position. In other words, an - * error from an included file. - * - * @param m - * @param translation - */ - private void adjustIndirectPosition(IMessage m, IJSPTranslation translation) { - - if (!(translation instanceof JSPTranslationExtension)) - return; - - IDocument jspDoc = ((JSPTranslationExtension) translation).getJspDocument(); - if (!(jspDoc instanceof IStructuredDocument)) - return; - - IStructuredDocument sDoc = (IStructuredDocument) jspDoc; - IStructuredDocumentRegion[] regions = sDoc.getStructuredDocumentRegions(0, m.getOffset() + m.getLength()); - // iterate backwards until you hit the include directive - for (int i = regions.length - 1; i >= 0; i--) { - IStructuredDocumentRegion region = regions[i]; - if (region.getType() == DOMJSPRegionContexts.JSP_DIRECTIVE_NAME) { - if (getDirectiveName(region).equals("include")) { //$NON-NLS-1$ - ITextRegion fileValueRegion = getAttributeValueRegion(region, "file"); //$NON-NLS-1$ - if (fileValueRegion != null) { - m.setOffset(region.getStartOffset(fileValueRegion)); - m.setLength(fileValueRegion.getTextLength()); - } - else { - m.setOffset(region.getStartOffset()); - m.setLength(region.getTextLength()); - } - /** - * Bug 219761 - Syntax error reported at wrong location - * (don't forget to adjust the line number, too) - */ - m.setLineNo(sDoc.getLineOfOffset(m.getOffset()) + 1); - break; - } - } - } - } - - /** - * Creates an IMessage from asn IProblem - * - * @param problem - * @param f - * @param translation - * @param structuredDoc - * @return message representation of the problem, or null if it could not - * create one - */ - private IMessage createMessageFromProblem(IProblem problem, IFile f, IJSPTranslation translation, IStructuredDocument structuredDoc) { - int sev = -1; - int sourceStart = -1; - int sourceEnd = -1; - - if (problem instanceof IJSPProblem) { - sourceStart = problem.getSourceStart(); - sourceEnd = problem.getSourceEnd(); - switch (((IJSPProblem) problem).getEID()) { - case IJSPProblem.TEIClassNotFound : - sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_TRANSLATION_TEI_CLASS_NOT_FOUND); - break; - case IJSPProblem.TEIValidationMessage : - sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_TRANSLATION_TEI_VALIDATION_MESSAGE); - break; - case IJSPProblem.TEIClassNotInstantiated : - sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_TRANSLATION_TEI_CLASS_NOT_INSTANTIATED); - break; - case IJSPProblem.TEIClassMisc : - sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_TRANSLATION_TEI_CLASS_RUNTIME_EXCEPTION); - break; - case IJSPProblem.TagClassNotFound : - sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_TRANSLATION_TAG_HANDLER_CLASS_NOT_FOUND); - break; - case IJSPProblem.UseBeanInvalidID : - sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_TRANSLATION_USEBEAN_INVALID_ID); - break; - case IJSPProblem.UseBeanMissingTypeInfo : - sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_TRANSLATION_USBEAN_MISSING_TYPE_INFO); - break; - case IJSPProblem.UseBeanAmbiguousType : - sev = getMessageSeverity(JSPCorePreferenceNames.VALIDATION_TRANSLATION_USEBEAN_AMBIGUOUS_TYPE_INFO); - break; - default : - sev = problem.isError() ? IMessage.HIGH_SEVERITY : (problem.isWarning() ? IMessage.NORMAL_SEVERITY : ValidationMessage.IGNORE); - - } - } - else { - sourceStart = translation.getJspOffset(problem.getSourceStart()); - sourceEnd = translation.getJspOffset(problem.getSourceEnd()); - switch (problem.getID()) { - case IProblem.LocalVariableIsNeverUsed : { - sev = getSourceSeverity(JSPCorePreferenceNames.VALIDATION_JAVA_LOCAL_VARIABLE_NEVER_USED, sourceStart, sourceEnd); - } - break; - case IProblem.NullLocalVariableReference : { - sev = getSourceSeverity(JSPCorePreferenceNames.VALIDATION_JAVA_NULL_LOCAL_VARIABLE_REFERENCE, sourceStart, sourceEnd); - } - break; - case IProblem.ArgumentIsNeverUsed : { - sev = getSourceSeverity(JSPCorePreferenceNames.VALIDATION_JAVA_ARGUMENT_IS_NEVER_USED, sourceStart, sourceEnd); - } - break; - case IProblem.PotentialNullLocalVariableReference : { - sev = getSourceSeverity(JSPCorePreferenceNames.VALIDATION_JAVA_POTENTIAL_NULL_LOCAL_VARIABLE_REFERENCE, sourceStart, sourceEnd); - } - break; - case IProblem.UnusedImport : { - sev = getSourceSeverity(JSPCorePreferenceNames.VALIDATION_JAVA_UNUSED_IMPORT, sourceStart, sourceEnd); - } - break; - case IProblem.UnusedPrivateField: - case IProblem.MissingSerialVersion : { - // JSP files don't get serialized...right? - sev = ValidationMessage.IGNORE; - } - break; - - default : { - if (problem.isError()) { - sev = IMessage.HIGH_SEVERITY; - } - else if (problem.isWarning()) { - sev = IMessage.NORMAL_SEVERITY; - } - else { - sev = IMessage.LOW_SEVERITY; - } - } - if (sev == ValidationMessage.IGNORE) { - return null; - } - - /* problems without JSP positions are in generated code */ - if (sourceStart == -1) { - int problemID = problem.getID(); - /* - * Quoting IProblem doc: "When a problem is tagged as - * Internal, it means that no change other than a - * local source code change can fix the corresponding - * problem." Assuming that our generated code is - * correct, that should reduce the reported problems - * to those the user can correct. - */ - if (((problemID & IProblem.Internal) != 0) && ((problemID & IProblem.Syntax) != 0) && translation instanceof JSPTranslation) { - // Attach to the last code scripting section - JSPTranslation jspTranslation = ((JSPTranslation) translation); - Position[] jspPositions = (Position[]) jspTranslation.getJsp2JavaMap().keySet().toArray(new Position[jspTranslation.getJsp2JavaMap().size()]); - for (int i = 0; i < jspPositions.length; i++) { - sourceStart = Math.max(sourceStart, jspPositions[i].getOffset()); - } - IMessage m = new LocalizedMessage(sev, problem.getMessage(), f); - m.setOffset(sourceStart); - m.setLength(1); - return m; - } - else { - return null; - } - } - } - } - if (sev == ValidationMessage.IGNORE) { - return null; - } - - // line number for marker starts @ 1 - // line number from document starts @ 0 - int lineNo = structuredDoc.getLineOfOffset(sourceStart) + 1; - - IMessage m = new LocalizedMessage(sev, problem.getMessage(), f); - - m.setLineNo(lineNo); - m.setOffset(sourceStart); - m.setLength(sourceEnd - sourceStart + 1); - - // need additional adjustment for problems from - // indirect (included) files - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=119633 - if (translation.isIndirect(problem.getSourceStart())) { - adjustIndirectPosition(m, translation); - } - - return m; - } - - /** - * Provides the severity for the given message key only when it's within the source range of the JSP (i.e., not boilerplate code). - * @param key the key to get the severity of - * @param start start within the JSP source - * @param end end wtihin the JSP source - * @return The message severity for the key if it is part of the JSP's source. IGNORE if it's boilerplate code. - */ - private int getSourceSeverity(String key, int start, int end) { - return (start >= 0 && end >= 0 ) ? getMessageSeverity(key) : ValidationMessage.IGNORE; - } - - int getMessageSeverity(String key) { - int sev = fPreferencesService.getInt(PREFERENCE_NODE_QUALIFIER, key, IMessage.NORMAL_SEVERITY, fScopes); - switch (sev) { - case ValidationMessage.ERROR : - return IMessage.HIGH_SEVERITY; - case ValidationMessage.WARNING : - return IMessage.NORMAL_SEVERITY; - case ValidationMessage.INFORMATION : - return IMessage.LOW_SEVERITY; - case ValidationMessage.IGNORE : - return ValidationMessage.IGNORE; - } - return IMessage.NORMAL_SEVERITY; - } - - private void loadPreferences(IFile file) { - fScopes = new IScopeContext[]{new InstanceScope(), new DefaultScope()}; - - if (file != null && file.isAccessible()) { - ProjectScope projectScope = new ProjectScope(file.getProject()); - if (projectScope.getNode(PREFERENCE_NODE_QUALIFIER).getBoolean(JSPCorePreferenceNames.VALIDATION_USE_PROJECT_SETTINGS, false)) { - fScopes = new IScopeContext[]{projectScope, new InstanceScope(), new DefaultScope()}; - } - } - } - - void performValidation(IFile f, IReporter reporter, IStructuredModel model) { - for (int i = 0; i < DEPEND_ONs.length; i++) { - addDependsOn(f.getProject().getFile(DEPEND_ONs[i])); - } - if (model instanceof IDOMModel) { - IDOMModel domModel = (IDOMModel) model; - ModelHandlerForJSP.ensureTranslationAdapterFactory(domModel); - - IDOMDocument xmlDoc = domModel.getDocument(); - JSPTranslationAdapter translationAdapter = (JSPTranslationAdapter) xmlDoc.getAdapterFor(IJSPTranslation.class); - IJSPTranslation translation = translationAdapter.getJSPTranslation(); - - if (!reporter.isCancelled()) { - loadPreferences(f); - - // only update task markers if the model is the same as what's on disk - boolean updateJavaTasks = UPDATE_JAVA_TASKS && !domModel.isDirty() && f != null && f.isAccessible(); - if (updateJavaTasks) { - // remove old Java task markers - try { - IMarker[] foundMarkers = f.findMarkers(JAVA_TASK_MARKER_TYPE, true, IResource.DEPTH_ONE); - for (int i = 0; i < foundMarkers.length; i++) { - foundMarkers[i].delete(); - } - } - catch (CoreException e) { - Logger.logException(e); - } - } - - translation.setProblemCollectingActive(true); - translation.reconcileCompilationUnit(); - List problems = translation.getProblems(); - // 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 (updateJavaTasks) { - // add new Java task marker - try { - IMarker task = f.createMarker(JAVA_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); - } - } - } - } - } - unloadPreferences(); - } - - private void unloadPreferences() { - fScopes = null; - } - - /** - * Validate one file. It's assumed that the file has JSP content type. - * - * @param f - * @param reporter - */ - protected void validateFile(IFile f, IReporter reporter) { - if (DEBUG) { - Logger.log(Logger.INFO, getClass().getName() + " validating: " + f); //$NON-NLS-1$ - } - - IStructuredModel model = null; - try { - // get jsp model, get tranlsation - model = StructuredModelManager.getModelManager().getModelForRead(f); - if (!reporter.isCancelled() && model != null) { - for (int i = 0; i < DEPEND_ONs.length; i++) { - addDependsOn(f.getProject().getFile(DEPEND_ONs[i])); - } - // get jsp model, get translation - if (model instanceof IDOMModel) { - reporter.removeAllMessages(fMessageOriginator, f); - performValidation(f, reporter, model); - } - } - } - catch (IOException e) { - Logger.logException(e); - } - catch (CoreException e) { - Logger.logException(e); - } - finally { - if (model != null) - model.releaseFromRead(); - } - } - - /** - * Record that the currently validating resource depends on the given - * file. Only possible during batch (not source) validation. - * - * @param file - */ - private void addDependsOn(IFile file) { - if (fMessageOriginator instanceof JSPBatchValidator) { - ((JSPBatchValidator) fMessageOriginator).addDependsOn(file); - } - } - -} diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPValidator.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPValidator.java deleted file mode 100644 index a6b20c157e..0000000000 --- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/JSPValidator.java +++ /dev/null @@ -1,420 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.jsp.core.internal.validation; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceProxy; -import org.eclipse.core.resources.IResourceProxyVisitor; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.jobs.ISchedulingRule; -import org.eclipse.jst.jsp.core.internal.Logger; -import org.eclipse.jst.jsp.core.internal.contentproperties.JSPFContentProperties; -import org.eclipse.jst.jsp.core.internal.provisional.contenttype.ContentTypeIdForJSP; -import org.eclipse.jst.jsp.core.internal.regions.DOMJSPRegionContexts; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionCollection; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; -import org.eclipse.wst.validation.AbstractValidator; -import org.eclipse.wst.validation.ValidationResult; -import org.eclipse.wst.validation.ValidationState; -import org.eclipse.wst.validation.internal.core.Message; -import org.eclipse.wst.validation.internal.core.ValidationException; -import org.eclipse.wst.validation.internal.operations.IWorkbenchContext; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidationContext; -import org.eclipse.wst.validation.internal.provisional.core.IValidatorJob; -import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext; - -/** - * Performs some common JSP validation tasks - */ -public class JSPValidator extends AbstractValidator implements IValidatorJob { - - private static final String PLUGIN_ID_JSP_CORE = "org.eclipse.jst.jsp.core"; //$NON-NLS-1$ - private IContentType fJSPFContentType = null; - - protected class LocalizedMessage extends Message { - - private String _message = null; - - public LocalizedMessage(int severity, String messageText) { - this(severity, messageText, null); - } - - public LocalizedMessage(int severity, String messageText, IResource targetObject) { - this(severity, messageText, (Object) targetObject); - } - - public LocalizedMessage(int severity, String messageText, Object targetObject) { - super(null, severity, null); - setLocalizedMessage(messageText); - setTargetObject(targetObject); - } - - public void setLocalizedMessage(String message) { - _message = message; - } - - public String getLocalizedMessage() { - return _message; - } - - public String getText() { - return getLocalizedMessage(); - } - - public String getText(ClassLoader cl) { - return getLocalizedMessage(); - } - - public String getText(Locale l) { - return getLocalizedMessage(); - } - - public String getText(Locale l, ClassLoader cl) { - return getLocalizedMessage(); - } - } - - protected class JSPFileVisitor implements IResourceProxyVisitor { - - private List fFiles = new ArrayList(); - private IContentType[] fContentTypes = null; - private IReporter fReporter = null; - - public JSPFileVisitor(IReporter reporter) { - fReporter = reporter; - } - - public boolean visit(IResourceProxy proxy) throws CoreException { - - // check validation - if (fReporter.isCancelled()) - return false; - - if (proxy.getType() == IResource.FILE) { - - if (isJSPType(proxy.getName())) { - IFile file = (IFile) proxy.requestResource(); - if (file.exists()) { - - if (DEBUG) - System.out.println("(+) JSPValidator adding file: " + file.getName()); //$NON-NLS-1$ - fFiles.add(file); - - // don't search deeper for files - return false; - } - } - } - return true; - } - - public final IFile[] getFiles() { - return (IFile[]) fFiles.toArray(new IFile[fFiles.size()]); - } - - /** - * Gets list of content types this visitor is interested in - * - * @return All JSP-related content types - */ - private IContentType[] getValidContentTypes() { - if (fContentTypes == null) { - // currently "hard-coded" to be jsp & jspf - fContentTypes = new IContentType[]{Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSP), Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT)}; - } - return fContentTypes; - } - - /** - * Checks if fileName is some type of JSP (including JSP fragments) - * - * @param fileName - * @return true if filename indicates some type of JSP, false - * otherwise - */ - private boolean isJSPType(String fileName) { - boolean valid = false; - - IContentType[] types = getValidContentTypes(); - int i = 0; - while (i < types.length && !valid) { - valid = types[i].isAssociatedWith(fileName); - ++i; - } - return valid; - } - } - - public void cleanup(IReporter reporter) { - // nothing to do - } - - public void validate(IValidationContext helper, IReporter reporter) throws ValidationException { - String[] uris = helper.getURIs(); - IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); - if (uris.length > 0) { - IFile currentFile = null; - - for (int i = 0; i < uris.length && !reporter.isCancelled(); i++) { - // might be called with just project path? - currentFile = wsRoot.getFile(new Path(uris[i])); - if (currentFile != null && currentFile.exists()) { - if (shouldValidate(currentFile) && fragmentCheck(currentFile)) { - - Message message = new LocalizedMessage(IMessage.LOW_SEVERITY, uris[i]); - reporter.displaySubtask(this, message); - - validateFile(currentFile, reporter); - } - if (DEBUG) - System.out.println("validating: [" + uris[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - else { - - // if uris[] length 0 -> validate() gets called for each project - if (helper instanceof IWorkbenchContext) { - - IProject project = ((IWorkbenchContext) helper).getProject(); - JSPFileVisitor visitor = new JSPFileVisitor(reporter); - try { - // collect all jsp files for the project - project.accept(visitor, IResource.DEPTH_INFINITE); - } - catch (CoreException e) { - if (DEBUG) - e.printStackTrace(); - } - IFile[] files = visitor.getFiles(); - for (int i = 0; i < files.length && !reporter.isCancelled(); i++) { - if (shouldValidate(files[i]) && fragmentCheck(files[i])) { - int percent = (i * 100) / files.length + 1; - Message message = new LocalizedMessage(IMessage.LOW_SEVERITY, percent + "% " + files[i].getFullPath().toString()); - reporter.displaySubtask(this, message); - - validateFile(files[i], reporter); - } - if (DEBUG) - System.out.println("validating: [" + files[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - } - - /** - * Validate one file. It's assumed that the file has JSP content type. - * - * @param f - * @param reporter - */ - protected void validateFile(IFile f, IReporter reporter) { - // subclasses should implement (for batch validation) - } - - public ValidationResult validate(final IResource resource, int kind, ValidationState state, IProgressMonitor monitor) { - if (resource.getType() != IResource.FILE) - return null; - ValidationResult result = new ValidationResult(); - final IReporter reporter = result.getReporter(monitor); - validateFile((IFile) resource, reporter); - return result; - } - - /** - * - * @param collection - * @return the jsp directive name - */ - protected String getDirectiveName(ITextRegionCollection collection) { - String name = ""; //$NON-NLS-1$ - ITextRegionList subRegions = collection.getRegions(); - for (int j = 0; j < subRegions.size(); j++) { - ITextRegion subRegion = subRegions.get(j); - if (subRegion.getType() == DOMJSPRegionContexts.JSP_DIRECTIVE_NAME) { - name = collection.getText(subRegion); - break; - } - } - return name; - } - - /** - * - * @param sdr - * @param attrName - * @return the ITextRegion for the attribute value of the given attribute - * name, case sensitive, null if no matching attribute is found - */ - protected ITextRegion getAttributeValueRegion(ITextRegionCollection sdr, String attrName) { - ITextRegion valueRegion = null; - ITextRegionList subRegions = sdr.getRegions(); - for (int i = 0; i < subRegions.size(); i++) { - ITextRegion subRegion = subRegions.get(i); - if (subRegion.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME && sdr.getText(subRegion).equals(attrName)) { - for (int j = i; j < subRegions.size(); j++) { - subRegion = subRegions.get(j); - if (subRegion.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE) { - valueRegion = subRegion; - break; - } - } - break; - } - } - return valueRegion; - } - - protected String getAttributeValue(ITextRegionCollection sdr, String attrName) { - ITextRegion r = getAttributeValueRegion(sdr, attrName); - if (r != null) - return sdr.getText(r).trim(); - return ""; //$NON-NLS-1$ - } - - /** - * Determines if file is jsp fragment or not (does a deep, indepth check, - * looking into contents of file) - * - * @param file - * assumes file is not null and exists - * @return true if file is jsp fragment, false otherwise - */ - private boolean isFragment(IFile file) { - boolean isFragment = false; - InputStream is = null; - try { - IContentDescription contentDescription = file.getContentDescription(); - // it can be null - if (contentDescription == null) { - is = file.getContents(); - contentDescription = Platform.getContentTypeManager().getDescriptionFor(is, file.getName(), new QualifiedName[]{IContentDescription.CHARSET}); - } - if (contentDescription != null) { - String fileCtId = contentDescription.getContentType().getId(); - isFragment = (fileCtId != null && ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT.equals(fileCtId)); - } - } - catch (IOException e) { - // ignore, assume it's invalid JSP - } - catch (CoreException e) { - // ignore, assume it's invalid JSP - } - finally { - // must close input stream in case others need it - if (is != null) - try { - is.close(); - } - catch (Exception e) { - // not sure how to recover at this point - } - } - return isFragment; - } - - private boolean shouldValidate(IFile file) { - IResource resource = file; - do { - if (resource.isDerived() || resource.isTeamPrivateMember() || !resource.isAccessible() || resource.getName().charAt(0) == '.') { - return false; - } - resource = resource.getParent(); - } - while ((resource.getType() & IResource.PROJECT) == 0); - return true; - } - - // for debugging - static final boolean DEBUG; - static { - String value = Platform.getDebugOption("org.eclipse.jst.jsp.core/debug/jspvalidator"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - /** - * Checks if file is a jsp fragment or not. If so, check if the fragment - * should be validated or not. - * - * @param file - * Assumes shouldValidate was already called on file so it - * should not be null and does exist - * @return false if file is a fragment and it should not be validated, - * true otherwise - */ - private boolean fragmentCheck(IFile file) { - boolean shouldValidate = true; - // quick check to see if this is possibly a jsp fragment - if (getJSPFContentType().isAssociatedWith(file.getName())) { - // get preference for validate jsp fragments - boolean shouldValidateFragments = Boolean.valueOf(JSPFContentProperties.getProperty(JSPFContentProperties.VALIDATE_FRAGMENTS, file, true)).booleanValue(); - /* - * if jsp fragments should not be validated, check if file is - * really jsp fragment - */ - if (!shouldValidateFragments) { - boolean isFragment = isFragment(file); - shouldValidate = !isFragment; - } - } - return shouldValidate; - } - - /** - * Returns JSP fragment content type - * - * @return jspf content type - */ - private IContentType getJSPFContentType() { - if (fJSPFContentType == null) { - fJSPFContentType = Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT); - } - return fJSPFContentType; - } - - public ISchedulingRule getSchedulingRule(IValidationContext helper) { - return null; - } - - public IStatus validateInJob(IValidationContext helper, IReporter reporter) throws ValidationException { - IStatus status = Status.OK_STATUS; - try { - validate(helper, reporter); - } - catch (ValidationException e) { - Logger.logException(e); - status = new Status(IStatus.ERROR, PLUGIN_ID_JSP_CORE, IStatus.ERROR, e.getLocalizedMessage(), e); - } - return status; - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/LocalizedMessage.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/LocalizedMessage.java deleted file mode 100644 index 7bd2f314ff..0000000000 --- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/LocalizedMessage.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jst.jsp.core.internal.validation; - -import java.util.Locale; - -import org.eclipse.core.resources.IResource; -import org.eclipse.wst.validation.internal.core.Message; - -/** - * Simple implementation of Message all validators in package can use. - */ -class LocalizedMessage extends Message { - private String _message = null; - - public LocalizedMessage(int severity, String messageText) { - this(severity, messageText, null); - } - - public LocalizedMessage(int severity, String messageText, IResource targetObject) { - this(severity, messageText, (Object) targetObject); - } - - public LocalizedMessage(int severity, String messageText, Object targetObject) { - super(null, severity, null); - setLocalizedMessage(messageText); - setTargetObject(targetObject); - } - - public void setLocalizedMessage(String message) { - _message = message; - } - - public String getLocalizedMessage() { - return _message; - } - - public String getText() { - return getLocalizedMessage(); - } - - public String getText(ClassLoader cl) { - return getLocalizedMessage(); - } - - public String getText(Locale l) { - return getLocalizedMessage(); - } - - public String getText(Locale l, ClassLoader cl) { - return getLocalizedMessage(); - } -} diff --git a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/TLDValidator.java b/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/TLDValidator.java deleted file mode 100644 index ae70a60a78..0000000000 --- a/bundles/org.eclipse.jst.jsp.core/src/org/eclipse/jst/jsp/core/internal/validation/TLDValidator.java +++ /dev/null @@ -1,219 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.jst.jsp.core.internal.validation; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.ProjectScope; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.preferences.DefaultScope; -import org.eclipse.core.runtime.preferences.IPreferencesService; -import org.eclipse.core.runtime.preferences.IScopeContext; -import org.eclipse.core.runtime.preferences.InstanceScope; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jst.jsp.core.internal.Assert; -import org.eclipse.jst.jsp.core.internal.JSPCoreMessages; -import org.eclipse.jst.jsp.core.internal.JSPCorePlugin; -import org.eclipse.jst.jsp.core.internal.Logger; -import org.eclipse.jst.jsp.core.internal.contentmodel.tld.provisional.JSP11TLDNames; -import org.eclipse.jst.jsp.core.internal.contentmodel.tld.provisional.JSP12TLDNames; -import org.eclipse.jst.jsp.core.internal.preferences.JSPCorePreferenceNames; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.validate.ValidationMessage; -import org.eclipse.wst.validation.AbstractValidator; -import org.eclipse.wst.validation.ValidationResult; -import org.eclipse.wst.validation.ValidationState; -import org.eclipse.wst.validation.ValidatorMessage; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - * A miniature validator for .tld files. Checks for valid class names. - */ -public class TLDValidator extends AbstractValidator { - private static final String MARKER_TYPE = "org.eclipse.jst.jsp.core.validationMarker"; //$NON-NLS-1$ - private static final String PREFERENCE_NODE_QUALIFIER = JSPCorePlugin.getDefault().getBundle().getSymbolicName(); - - private IPreferencesService fPreferencesService = Platform.getPreferencesService(); - - private static final String[] classElementNames = new String[]{JSP11TLDNames.TAGCLASS, JSP12TLDNames.TAG_CLASS, JSP11TLDNames.TEICLASS, JSP12TLDNames.TEI_CLASS, JSP12TLDNames.VALIDATOR_CLASS, JSP12TLDNames.VARIABLE_CLASS, JSP12TLDNames.LISTENER_CLASS}; - private static final String[] missingClassMessages = new String[]{JSPCoreMessages.TaglibHelper_3, JSPCoreMessages.TaglibHelper_3, JSPCoreMessages.TaglibHelper_0, JSPCoreMessages.TaglibHelper_0, JSPCoreMessages.TLDValidator_MissingValidator, JSPCoreMessages.TLDValidator_MissingVariable, JSPCoreMessages.TLDValidator_MissingListener}; - private static final String[] missingClassSeverityPreferenceKeys = new String[]{JSPCorePreferenceNames.VALIDATION_TRANSLATION_TAG_HANDLER_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TAG_HANDLER_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TEI_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TEI_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TAG_HANDLER_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TAG_HANDLER_CLASS_NOT_FOUND, JSPCorePreferenceNames.VALIDATION_TRANSLATION_TAG_HANDLER_CLASS_NOT_FOUND}; - - public TLDValidator() { - super(); - - Assert.isTrue(classElementNames.length == missingClassMessages.length, "mismanaged arrays"); //$NON-NLS-1$ - Assert.isTrue(classElementNames.length == missingClassSeverityPreferenceKeys.length, "mismanaged arrays"); //$NON-NLS-1$ - Assert.isTrue(missingClassMessages.length == missingClassSeverityPreferenceKeys.length, "mismanaged arrays"); //$NON-NLS-1$ - } - - private Map checkClass(IJavaProject javaProject, Node classSpecifier, IScopeContext[] preferenceScopes, String preferenceKey, String errorMessage) { - String className = getTextContents(classSpecifier); - if (className != null && className.length() > 2) { - IType type = null; - try { - type = javaProject.findType(className); - } - catch (JavaModelException e) { - return null; - } - - if (type == null || !type.exists()) { - Object severity = getMessageSeverity(preferenceScopes, preferenceKey); - if (severity == null) - return null; - - IDOMNode classElement = (IDOMNode) classSpecifier; - Map markerValues = new HashMap(); - markerValues.put(IMarker.SEVERITY, severity); - int start = classElement.getStartOffset(); - if (classElement.getStartStructuredDocumentRegion() != null && classElement.getEndStructuredDocumentRegion() != null) - start = classElement.getStartStructuredDocumentRegion().getEndOffset(); - markerValues.put(IMarker.CHAR_START, new Integer(start)); - int end = classElement.getEndOffset(); - if (classElement.getStartStructuredDocumentRegion() != null && classElement.getEndStructuredDocumentRegion() != null) - end = classElement.getEndStructuredDocumentRegion().getStartOffset(); - markerValues.put(IMarker.CHAR_END, new Integer(end)); - int line = classElement.getStructuredDocument().getLineOfOffset(start); - markerValues.put(IMarker.LINE_NUMBER, new Integer(line + 1)); - markerValues.put(IMarker.MESSAGE, NLS.bind(errorMessage, (errorMessage.indexOf("{1}") >= 0) ? new String[]{getTagName(classSpecifier), className} : new String[]{className})); //$NON-NLS-1$ - return markerValues; - } - } - return null; - } - - private Map[] detectProblems(IJavaProject javaProject, IFile tld, IScopeContext[] preferenceScopes) throws CoreException { - List problems = new ArrayList(); - - IStructuredModel m = null; - try { - m = StructuredModelManager.getModelManager().getModelForRead(tld); - if (m != null && m instanceof IDOMModel) { - IDOMDocument document = ((IDOMModel) m).getDocument(); - - for (int i = 0; i < classElementNames.length; i++) { - NodeList classes = document.getElementsByTagName(classElementNames[i]); - for (int j = 0; j < classes.getLength(); j++) { - Map problem = checkClass(javaProject, classes.item(j), preferenceScopes, missingClassSeverityPreferenceKeys[i], missingClassMessages[i]); - if (problem != null) - problems.add(problem); - } - } - - } - } - catch (IOException e) { - Logger.logException(e); - } - finally { - if (m != null) - m.releaseFromRead(); - } - - return (Map[]) problems.toArray(new Map[problems.size()]); - } - - Integer getMessageSeverity(IScopeContext[] preferenceScopes, String key) { - int sev = fPreferencesService.getInt(PREFERENCE_NODE_QUALIFIER, key, IMessage.NORMAL_SEVERITY, preferenceScopes); - switch (sev) { - case ValidationMessage.ERROR : - return new Integer(IMarker.SEVERITY_ERROR); - case ValidationMessage.WARNING : - return new Integer(IMarker.SEVERITY_WARNING); - case ValidationMessage.INFORMATION : - return new Integer(IMarker.SEVERITY_INFO); - case ValidationMessage.IGNORE : - return null; - } - return new Integer(IMarker.SEVERITY_WARNING); - } - - private String getTagName(Node classSpecifier) { - Node tagElement = classSpecifier.getParentNode(); - Node child = tagElement.getFirstChild(); - while (child != null) { - if (child.getNodeType() == Node.ELEMENT_NODE) { - String name = child.getNodeName(); - if (JSP11TLDNames.NAME.equals(name)) - return getTextContents(child); - } - child = child.getNextSibling(); - } - return ""; - } - - private String getTextContents(Node parent) { - NodeList children = parent.getChildNodes(); - if (children.getLength() == 1) { - return children.item(0).getNodeValue().trim(); - } - StringBuffer s = new StringBuffer(); - Node child = parent.getFirstChild(); - while (child != null) { - s.append(child.getNodeValue().trim()); - child = child.getNextSibling(); - } - return s.toString().trim(); - } - - public ValidationResult validate(IResource resource, int kind, ValidationState state, IProgressMonitor monitor) { - if (resource.getType() != IResource.FILE) - return null; - ValidationResult result = new ValidationResult(); - - IFile tld = (IFile) resource; - if (tld.isAccessible()) { - try { - final IJavaProject javaProject = JavaCore.create(tld.getProject()); - if (javaProject.exists()) { - IScopeContext[] scopes = new IScopeContext[]{new InstanceScope(), new DefaultScope()}; - ProjectScope projectScope = new ProjectScope(tld.getProject()); - if (projectScope.getNode(PREFERENCE_NODE_QUALIFIER).getBoolean(JSPCorePreferenceNames.VALIDATION_USE_PROJECT_SETTINGS, false)) { - scopes = new IScopeContext[]{projectScope, new InstanceScope(), new DefaultScope()}; - } - Map[] problems = detectProblems(javaProject, tld, scopes); - for (int i = 0; i < problems.length; i++) { - ValidatorMessage message = ValidatorMessage.create(problems[i].get(IMarker.MESSAGE).toString(), resource); - message.setType(MARKER_TYPE); - message.setAttributes(problems[i]); - result.add(message); - } - } - } - catch (Exception e) { - Logger.logException(e); - } - } - - return result; - } -} |