diff options
Diffstat (limited to 'plugins/org.eclipse.wst.validation/vf2/org')
65 files changed, 0 insertions, 12113 deletions
diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/AbstractValidator.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/AbstractValidator.java deleted file mode 100644 index 83c1d55aa..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/AbstractValidator.java +++ /dev/null @@ -1,194 +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.wst.validation; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.wst.validation.Validator.V2; - -/** - * The class that all Validators that wish to use version two of the validation framework must subclass. - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @author karasiuk - * - */ -public abstract class AbstractValidator { - - private V2 _parent; - - /** - * Validate the resource. The validator is called from a WorkspaceJob, so - * the validator itself does not need to establish it's own IWorkspaceRunnable. - * <p> - * If you override this method then you should not override the other validate method. - * </p> - * - * @param resource - * The resource to be validated. - * - * @param kind - * The way the resource changed. It uses the same values as the kind - * parameter in IResourceDelta. - * - * @param state - * A way to pass arbitrary, validator specific, data from one - * invocation of a validator to the next, during the validation phase. - * At the end of the validation phase, this object will be cleared, - * thereby allowing any of this state information to be garbaged - * collected. - * - * @param monitor - * A monitor that you can use to report your progress. To be a well - * behaved validator you need to check the isCancelled() method at - * appropriate times. - * - * @return the result of the validation. This may be, but usually isn't, null. - */ - public ValidationResult validate(IResource resource, int kind, ValidationState state, IProgressMonitor monitor){ - return null; - } - - /** - * Validate the resource. The validator is called from a WorkspaceJob, so - * the validator itself does not need to establish it's own - * IWorkspaceRunnable. - * <p> - * If you override this method then you should not override the other - * validate method. - * </p> - * - * @param event - * An object that describes the resource to be validated and why - * it should be validated. - * - * @param state - * A way to pass arbitrary, validator specific, data from one - * invocation of a validator to the next, during the validation - * phase. At the end of the validation phase, this object will be - * cleared, thereby allowing any of this state information to be - * garbaged collected. - * - * @param monitor - * A monitor that you can use to report your progress. To be a - * well behaved validator you need to check the isCancelled() - * method at appropriate times. - * - * @return the result of the validation. Null should never be returned. If - * null is returned then the other validate method will be called as - * well. - */ - public ValidationResult validate(ValidationEvent event, ValidationState state, IProgressMonitor monitor){ - return null; - } - - - /** - * A call back method that lets the validator know that the project is being - * cleaned. This method gives the validator a chance to do any special - * cleanup. The default is to do nothing. - * <p> - * If the entire workspace is being cleaned, then the first call will have a - * null project, and then there will be subsequent calls for each open - * project in the workspace.</p> - * - * @param project - * The project being cleaned. This may be null, which is an indication - * that the workspace is being cleaned. - * - * @param state - * A way to pass arbitrary, validator specific, data from one - * invocation of a validator to the next, during the validation phase. - * - * @param monitor - * The monitor that should be used for reporting progress if the clean - * takes a long time. - */ - public void clean(IProject project, ValidationState state, IProgressMonitor monitor){ - } - - /** - * This method is called before any validation takes place. It allows - * validators to perform any initialization that they might need. - * - * @param project - * The project that is being validated. For the very first call in the - * validation phase, this will be null. A null project is the signal - * that a top level validation is starting. Subsequently, the project - * will be set, as each of the individual projects are validated. - * - * @param state - * A way to pass arbitrary, validator specific, data from one - * invocation of a validator to the next, during the validation phase. - * - * @param monitor - * The monitor that should be used for reporting progress if the initialization - * takes a long time. - */ - public void validationStarting(IProject project, ValidationState state, IProgressMonitor monitor){ - } - - /** - * This method will be called when validation is complete. It allows - * validators to perform any cleanup that they might need to do. - * - * @param project - * The project that was validated. The very last call in the validation - * sets this to null so that the validator knows that all the - * projects have now been validated. - * - * @param state - * A way to pass arbitrary, validator specific, data from one - * invocation of a validator to the next, during the validation phase. - * - * @param monitor - * The monitor that should be used for reporting progress if the cleanup - * takes a long time. - */ - public void validationFinishing(IProject project, ValidationState state, IProgressMonitor monitor){ - } - - /** - * Should the validation framework first clear the markers that this - * validator has placed on this resource? This method can be overridden by - * validator implementors to provide a validator specific behavior. - * - * @param event - * The validation event that triggered the validation. - * @return true if the validation framework should first clear all the - * markers that this validator produced. This is the default - * behavior. Return false to leave the markers unchanged. It then - * becomes the responsibility of the validator to manage it's own - * markers for this resource, for this validation event. - */ - public boolean shouldClearMarkers(ValidationEvent event){ - return true; - } - - /** - * Answer the validator that you belong to. The validator controls the - * filters and various other settings. - * - * @nooverride - */ - public V2 getParent(){ - return _parent; - } - - void setParent(V2 parent){ - _parent = parent; - } -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/DependentResource.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/DependentResource.java deleted file mode 100644 index 3f1c67d86..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/DependentResource.java +++ /dev/null @@ -1,55 +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.wst.validation; - -import org.eclipse.core.resources.IResource; - -/** - * A resource that is dependent on another resource. - * <p> - * This is returned by the IDependencyIndex. - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @noextend - * @see IDependencyIndex - * @author karasiuk - * - */ -public class DependentResource { - private IResource _resource; - private Validator _validator; - - /** - * @noreference - */ - public DependentResource(IResource resource, Validator validator){ - _resource = resource; - _validator = validator; - } - - /** - * Answer the resource that is depended on. - */ - public IResource getResource() { - return _resource; - } - - /** - * Answer the validator that asserted the dependency. - */ - public Validator getValidator() { - return _validator; - } -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Friend.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Friend.java deleted file mode 100644 index 41466368d..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Friend.java +++ /dev/null @@ -1,57 +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.wst.validation; - -import java.util.Map; - -import org.eclipse.core.resources.IResource; -import org.eclipse.wst.validation.internal.ContentTypeWrapper; -import org.eclipse.wst.validation.internal.ValType; - -/** - * This class is only to be called by the validation framework and it's test cases. - * This class is NOT part of the API. - * <p> - * This class provides access to some internal methods. - * </p> - * @author karasiuk - * - */ -public class Friend { - - public static void setMessages(Validator validator, Map<String, MessageSeveritySetting> map) { - validator.setMessages(map); - } - - /** - * Has the validator's implementation been loaded yet? This is used by some test cases to ensure that - * plug-ins are not loaded too early. - */ - public static boolean isLoaded(Validator validator){ - return validator.isLoaded(); - } - - public static boolean shouldValidate(Validator validator, IResource resource, boolean isManual, boolean isBuild, - ContentTypeWrapper contentTypeWrapper){ - return validator.shouldValidate(resource, isManual, isBuild, contentTypeWrapper); - } - - public static boolean shouldValidate(Validator validator, IResource resource, ValType valType, - ContentTypeWrapper contentTypeWrapper){ - - return validator.shouldValidate(resource, valType, contentTypeWrapper); - } - - public static void setMigrated(Validator validator, boolean migrated){ - validator.setMigrated(migrated); - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IDependencyIndex.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IDependencyIndex.java deleted file mode 100644 index d9d494bd5..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IDependencyIndex.java +++ /dev/null @@ -1,112 +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.wst.validation; - -import java.util.List; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; - -/** - * This service is used to specify the resources that a particular resource depends on. - * <p> - * This is an optional service, validators do not need to use this Interface and can simply supply - * their dependency information through the ValidationResult return result. - * </p> - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @noimplement - * @see ValidationResult - * @author karasiuk - * - */ -public interface IDependencyIndex { - - /** - * Assert that one resource depends on another resource as part of it's validity. - * <p> - * For example, if an XML file is dependent on an XSD file to be valid, the - * resource that holds the XML file would be the dependent, and the resource - * that holds the XSD would be the dependsOn. - * </p> - * - * @param id - * The validator id that is asserting that the dependency exists. - * @param dependent - * The resource that is dependent on the other resource. For example a XML file. - * @param dependsOn - * The resource that this being depended on. For example a XSD file. - */ - void add(String id, IResource dependent, IResource dependsOn); - - /** - * Remove all the dependency assertions for this project. - * - * @param project - * The project that will have it's dependency assertions removed. - */ - void clear(IProject project); - - /** - * Answer all the resources that depend on this resource. For example, if - * this resource was a XSD, this could answer all the XML files that - * depended on it for their validity. - * - * @param resource - * A resource that other resources may depend on. - * - * @return the dependent resources. - */ - List<DependentResource> get(IResource resource); - - /** - * Answer all the resources that depend on this resource. For example, if - * this resource was a XSD, this could answer all the XML files that - * depended on it for their validity. - * - * @param id - * The validator id that asserted that the dependency exists. - * @param resource - * A resource that other resources may depend on. - * - * @return the dependent resources. This method can return null or an empty array, if - * there are no dependent resources. - */ - IResource[] get(String id, IResource resource); - - /** - * Answer true if other resources depend on this resource. - * - * @param resource - * The resource being tested. - * - * @return true if any of the validators asserted a dependency on this resource. - */ - boolean isDependedOn(IResource resource); - - /** - * Replace all the resources that the dependent depends on. - * - * @param id - * The validator id that is asserting that the dependency exists. - * @param dependent - * The resource that is dependent on the other resource. - * @param dependsOn - * All the resources that are depended on. This can be null or a zero - * length array. Null or a zero length array removes all the dependencies. - */ - void set(String id, IResource dependent, IResource[] dependsOn); - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IMutableValidator.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IMutableValidator.java deleted file mode 100644 index bbb6627c9..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IMutableValidator.java +++ /dev/null @@ -1,77 +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.wst.validation; - -/** - * A validator that has fields that can be updated. - * <p> - * The following procedure is used to change a Validator's settings. - * <ol> - * <li>An IMutableValidator is retrieved.</li> - * <li>The IMutableValidator is changed.</li> - * <li>The IMutableValidator is "activated".</li> - * </ol> - * </p> - * <p>The methods {@link ValidationFramework#getProjectSettings(org.eclipse.core.resources.IProject)} and - * {@link ValidationFramework#getWorkspaceSettings()} can be used to retrieve IMutableValidator's. - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - - * @author karasiuk - * - */ -public interface IMutableValidator { - - /** - * Answer the validator's id. - * @return - */ - String getId(); - - /** - * Answer the validator's name. - * @return - */ - String getName(); - - /** - * Answer the validator's class name. - * @return - */ - String getValidatorClassname(); - - /** - * Answer if the validator is enabled for build based validation. - */ - boolean isBuildValidation(); - - /** - * Answer if the validator is enabled for manual based validation. - */ - boolean isManualValidation(); - - /** - * Set whether the validator should be enabled for build based validation. - */ - void setBuildValidation(boolean build); - - /** - * Set whether the validator should be enabled for manual based validation. - */ - void setManualValidation(boolean manual); - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IPerformanceMonitor.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IPerformanceMonitor.java deleted file mode 100644 index b951270c5..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IPerformanceMonitor.java +++ /dev/null @@ -1,79 +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.wst.validation; - -import java.util.List; - -/** - * A service that collects performance information on validation operations. - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - * @author karasiuk - * - */ -public interface IPerformanceMonitor { - - /** - * The level of information to collect. - */ - public enum CollectionLevel {None, Default} - - /** - * Add this performance counter to the monitor. The monitor will decide what to - * do with the results, it may log them to a file, or it may simply hold on to them. - * - * @param counters - */ - public void add(PerformanceCounters counters); - - /** - * Answer true if the performance monitor is collecting performance events. - */ - public boolean isCollecting(); - - /** Answer true if only summary information is requested. */ - public boolean isSummaryOnly(); - - /** - * Set the performance event collection level. This controls which - * performance events are collected, including none of them. - * - * @param level - * The level to collect. The default is to not collect anything. - */ - public void setCollectionLevel(CollectionLevel level); - - /** - * Answer the level of performance events that are being collected by the validation framework. - */ - public CollectionLevel getCollectionLevel(); - - /** - * Answer the performance counters that have been collected so far. Some - * monitors do not save counters, and they will always return an empty list. - * - * @param asSummary - * If this parameter is true, only answer a summary of the counters. - */ - public List<PerformanceCounters> getPerformanceCounters(boolean asSummary); - - /** - * Delete the collected performance counters. - */ - public void resetPerformanceCounters(); - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IValidatorGroupListener.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IValidatorGroupListener.java deleted file mode 100644 index 5f4feee08..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/IValidatorGroupListener.java +++ /dev/null @@ -1,64 +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.wst.validation; - -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IProgressMonitor; - -/** - * Validators may wish to join validator groups for performance or other - * reasons. That way expensive operations like creating and releasing models can - * be done in a common location, and be done only once per resource. Group listeners - * are declared via the <code>org.eclipse.wst.validation.validatorGroup</code> extension point. - * <p> - * As validation proceeds, the validation framework, on a resource by resource - * bases, determines if any validators that are members of a group are - * interested in the resource. If they are, before the first validator in the - * group is called, the <code>validationStarting</code> method is called. If this method was - * called, then the <code>validationFinishing</code> method will be called once all the - * validators have processed the resource. - * </p> - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - */ -public interface IValidatorGroupListener { - /** - * This is called before the first validator in the group that is interested - * in the resource is called. If no validators in the group are interested - * in the resource, then this method is not called. - * - * @param resource - * The resource that is being validated. - * @param monitor - * A progress monitor that the method should use. - * @param state - * The validation state for the current operation. - */ - void validationStarting(IResource resource, IProgressMonitor monitor, ValidationState state); - - /** - * If the validationStarting method was called on the resource, then this - * method will be called after the last validator has processed the - * resource. - * - * @param resource - * The resource that is being validated. - * @param monitor - * A progress monitor that the method can use. - * @param state - * The validation state for the current operation. - */ - void validationFinishing(IResource resource, IProgressMonitor monitor, ValidationState state); -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MessageSeveritySetting.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MessageSeveritySetting.java deleted file mode 100644 index 4eaa3b776..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MessageSeveritySetting.java +++ /dev/null @@ -1,140 +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.wst.validation; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.wst.validation.internal.ValMessages; - -/** - * Associate a message severity with a message category. - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @noextend - * @author karasiuk - * - */ -public class MessageSeveritySetting { - public enum Severity { - Error(ValMessages.SevError, IMarker.SEVERITY_ERROR), - Warning(ValMessages.SevWarning, IMarker.SEVERITY_WARNING), - Ignore(ValMessages.SevIgnore, IMarker.SEVERITY_INFO); - - private String _severityLabel; - private Severity(String label, int markerSeverity){ - _severityLabel = label; - _markerSeverity = markerSeverity; - } - private int _markerSeverity; - - @Override - public String toString() { - return _severityLabel; - } - - /** - * Answer the associated IMarker severity. - */ - public int getMarkerSeverity() { - return _markerSeverity; - } - - } - - private String _id; - private String _label; - private Severity _default; - private Severity _current; - - /** - * Create an association between a label and a message severity. - * - * @param id - * An id that is used to identify this particular setting. This must be - * unique within the scope of this particular validator. - * - * @param label - * An end user string, that can describe either an individual message - * or a message category. - * - * @param defaultSeverity - * The default severity for this label. If the end user doesn't change - * anything this is what the severity will be. - */ - public MessageSeveritySetting(String id, String label, Severity defaultSeverity){ - _id = id; - _label = label; - _default = defaultSeverity; - } - - @Override - public int hashCode() { - int h = 0; - if (_current != null)h += _current.getMarkerSeverity()*1000; - if (_id != null)h += _id.hashCode(); - return h; - } - - public String getLabel() { - return _label; - } - - /** Answer the default severity as defined by the validator owner. */ - public Severity getDefault() { - return _default; - } - - /** - * Answer the current severity for the message. The end user may have changed this through a - * preference dialog. - */ - public Severity getCurrent() { - if (_current != null)return _current; - return _default; - } - - /** - * The id that the validator owner assigned to the message. - */ - public String getId() { - return _id; - } - - /** - * Set the current message severity. - * - * @param severity - * @return true if the setting changed - */ - public boolean setCurrent(Severity severity) { - if (_current == severity)return false; - _current = severity; - return true; - } - - @Override - public String toString() { - return _id + " " + getCurrent().toString(); //$NON-NLS-1$ - } - - /** - * Answer a copy of this object. - */ - public MessageSeveritySetting copy() { - MessageSeveritySetting ms = new MessageSeveritySetting(_id, _label, _default); - ms._current = _current; - return ms; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableProjectSettings.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableProjectSettings.java deleted file mode 100644 index 73bf21cae..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableProjectSettings.java +++ /dev/null @@ -1,96 +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.wst.validation; - -import org.eclipse.core.resources.IProject; - -/** - * This class holds the overall project validation settings. - * <p> - * The following procedure is used to change a project's Validation settings. - * <ol> - * <li>The MutableProjectSettings are retrieved.</li> - * <li>The MutableProjectSettings are changed.</li> - * <li>The MutableProjectSettings are "applied".</li> - * </ol> - * </p> - * <p>In order for a project's validation setting to be effective, both - * {@link #getOverride()} and {@link MutableWorkspaceSettings#getOverride()} - * must be true. - * </p> - * <p> - * These settings can be retrieved with {@link ValidationFramework#getProjectSettings(IProject)}. - * </p> - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - - * @author karasiuk - * - */ -public final class MutableProjectSettings { - private final IProject _project; - - private boolean _override; - private boolean _suspend; - private final IMutableValidator[] _validators; - - public IMutableValidator[] getValidators() { - return _validators; - } - - public MutableProjectSettings(IProject project, IMutableValidator[] validators){ - _project = project; - _validators = validators; - } - - /** - * Can this project override the workspace level validation settings? - */ - public boolean getOverride() { - return _override; - } - - /** - * Change whether this project can override workspace level validation settings. - * @param override Set to true if the project is allowed to override workspace level validation settings. - */ - public void setOverride(boolean override) { - _override = override; - } - - /** - * Is validation suspended for this project? - */ - public boolean getSuspend() { - return _suspend; - } - - /** - * Change whether this project is suspending it's validation. - * @param suspend Set to true, to suspend validation for this project. - */ - public void setSuspend(boolean suspend) { - _suspend = suspend; - } - - /** - * Answer the project that these settings are for. - */ - public IProject getProject() { - return _project; - } - - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableWorkspaceSettings.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableWorkspaceSettings.java deleted file mode 100644 index 80d18f112..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/MutableWorkspaceSettings.java +++ /dev/null @@ -1,96 +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.wst.validation; - -import org.eclipse.wst.validation.internal.model.GlobalPreferencesValues; - - -/** - * This class holds the overall workspace validation settings. - * <p> - * The following procedure is used to change a project's Validation settings. - * <ol> - * <li>The MutableWorkspaceSettings are retrieved.</li> - * <li>The MutableWorkspaceSettings are changed.</li> - * <li>The MutableWorkspaceSettings are "applied".</li> - * </ol> - * </p> - * <p> - * These settings can be retrieved with {@link ValidationFramework#getWorkspaceSettings()}. - * </p> - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - - * @author karasiuk - * - */ -public final class MutableWorkspaceSettings { - - private final GlobalPreferencesValues _values; - - private final IMutableValidator[] _validators; - - public IMutableValidator[] getValidators() { - return _validators; - } - - public MutableWorkspaceSettings(IMutableValidator[] validators, GlobalPreferencesValues values){ - _validators = validators; - _values = values; - } - - public GlobalPreferencesValues getGlobalPreferencesValues(){ - return _values; - } - - public boolean getAutoSave() { - return _values.saveAutomatically; - } - - public void setAutoSave(boolean autoSave) { - _values.saveAutomatically = autoSave; - } - - /** - * Can this project override the workspace level validation settings? - */ - public boolean getOverride() { - return _values.override; - } - - /** - * Change whether this project can override workspace level validation settings. - * @param override Set to true if the project is allowed to override workspace level validation settings. - */ - public void setOverride(boolean override) { - _values.override = override; - } - - /** - * Is validation suspended for this project? - */ - public boolean getSuspend() { - return _values.disableAllValidation; - } - - /** - * Change whether this project is suspending it's validation. - * @param suspend Set to true, to suspend validation for this project. - */ - public void setSuspend(boolean suspend) { - _values.disableAllValidation = suspend; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/PerformanceCounters.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/PerformanceCounters.java deleted file mode 100644 index cf577219b..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/PerformanceCounters.java +++ /dev/null @@ -1,116 +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.wst.validation; - -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.validation.internal.Misc; -import org.eclipse.wst.validation.internal.ValMessages; - -/** - * Some performance information for a validation invocation. This object is immutable. - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @noextend - * @author karasiuk - * - */ -public class PerformanceCounters { - - private long _when; - private String _validatorId; - private String _validatorName; - private String _resourceName; - private int _numberInvocations; - private long _elapsedTime; - private long _cpuTime; - - /** - * @param validatorId - * @param validatorName - * @param resourceName - * @param numberInvocations number of times the validator was invoked - * @param elapsedTime elapsed time in milliseconds - * @param cpuTime CPU time in nanoseconds - */ - public PerformanceCounters(String validatorId, String validatorName, String resourceName, - int numberInvocations, long elapsedTime, long cpuTime){ - - _when = System.currentTimeMillis(); - _validatorId = validatorId; - _validatorName = validatorName; - _resourceName = resourceName; - _numberInvocations = numberInvocations; - _elapsedTime = elapsedTime; - _cpuTime = cpuTime; - } - - public String getValidatorId() { - return _validatorId; - } - public int getNumberInvocations() { - return _numberInvocations; - } - - /** - * Answer the elapsed time in milliseconds. - */ - public long getElapsedTime() { - return _elapsedTime; - } - - /** - * Answer the amount of CPU time in nanoseconds. If this can not be determined, - * answer -1. - */ - public long getCpuTime() { - return _cpuTime; - } - - @Override - public String toString() { - return NLS.bind(ValMessages.LogValEndTime, - new Object[]{_validatorName, _validatorId, _resourceName, Misc.getTimeMS(_elapsedTime)}); - } - - public String toString(boolean asSummary){ - if (asSummary){ - if (_cpuTime != -1)return NLS.bind(ValMessages.LogValSummary2, - new Object[]{_validatorName, _validatorId, _numberInvocations, - Misc.getTimeMS(_elapsedTime), Misc.getTimeNano(_cpuTime)}); - - return NLS.bind(ValMessages.LogValSummary, - new Object[]{_validatorName, _validatorId, _numberInvocations, Misc.getTimeMS(_elapsedTime)}); - } - return toString(); - } - - public String getValidatorName() { - return _validatorName; - } - - /** - * Answer when was the event logged. - * - * @see System#currentTimeMillis() - */ - public long getWhen() { - return _when; - } - - public String getResourceName() { - return _resourceName; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ReporterHelper.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ReporterHelper.java deleted file mode 100644 index 20876bfd6..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ReporterHelper.java +++ /dev/null @@ -1,70 +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.wst.validation; - -import java.util.LinkedList; -import java.util.List; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.wst.validation.internal.MarkerManager; -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; - - -/** - * This is a temporary class to ease the transition from the previous validation framework. - * <p> - * This is not API. - * @author karasiuk - * - */ -public class ReporterHelper implements IReporter { - private IProgressMonitor _monitor; - private List<IMessage> _list = new LinkedList<IMessage>(); - - public ReporterHelper(IProgressMonitor monitor){ - _monitor = monitor; - } - - public void addMessage(IValidator origin, IMessage message) { - _list.add(message); - } - - public void displaySubtask(IValidator validator, IMessage message) { - _monitor.subTask(message.getText(validator.getClass().getClassLoader())); - } - - public List<IMessage> getMessages() { - return _list; - } - - public boolean isCancelled() { - return _monitor.isCanceled(); - } - - public void removeAllMessages(IValidator origin) { - _list.clear(); - } - - public void removeAllMessages(IValidator origin, Object object) { - _list.clear(); - } - - public void removeMessageSubset(IValidator validator, Object obj, String groupName) { - _list.clear(); - } - - public void makeMarkers(){ - MarkerManager.getDefault().makeMarkers(_list); - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationEvent.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationEvent.java deleted file mode 100644 index 528e58e35..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationEvent.java +++ /dev/null @@ -1,75 +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.wst.validation; - -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceDelta; - -/** - * An object that describes which object should be validated and what triggered its validation. - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @author karasiuk - * - */ - -public final class ValidationEvent { - - private IResource _resource; - private int _kind; - private IResourceDelta _dependsOn; - - /** - * Create an object that describes what should be validated. - * - * @param resource - * The resource to be validated. - * @param kind - * The way the resource changed. It uses the same values as the - * kind parameter in IResourceDelta. - * @param dependsOn - * If the resource is being validated because one of it's - * dependencies has changed, that change is described here. This - * can be null. - */ - public ValidationEvent(IResource resource, int kind, IResourceDelta dependsOn){ - _resource = resource; - _kind = kind; - _dependsOn = dependsOn; - } - - /** - * The resource to be validated. - */ - public IResource getResource() { - return _resource; - } - - /** - * The way the resource changed. It uses the same values as the kind - * parameter in IResourceDelta. - */ - public int getKind() { - return _kind; - } - - /** - * If the resource is being validated because one of it's dependencies has changed, that change is described here. - * This method will return null when the trigger is not because of a dependency change. - */ - public IResourceDelta getDependsOn() { - return _dependsOn; - } -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationFramework.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationFramework.java deleted file mode 100644 index 17cc455fd..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationFramework.java +++ /dev/null @@ -1,683 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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.wst.validation; - -import java.lang.reflect.InvocationTargetException; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -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.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.core.runtime.preferences.IEclipsePreferences; -import org.eclipse.core.runtime.preferences.InstanceScope; -import org.eclipse.wst.validation.Validator.V1; -import org.eclipse.wst.validation.internal.ConfigurationManager; -import org.eclipse.wst.validation.internal.ContentTypeWrapper; -import org.eclipse.wst.validation.internal.DebugConstants; -import org.eclipse.wst.validation.internal.DependencyIndex; -import org.eclipse.wst.validation.internal.DisabledResourceManager; -import org.eclipse.wst.validation.internal.DisabledValidatorManager; -import org.eclipse.wst.validation.internal.GlobalConfiguration; -import org.eclipse.wst.validation.internal.MarkerManager; -import org.eclipse.wst.validation.internal.Misc; -import org.eclipse.wst.validation.internal.PerformanceMonitor; -import org.eclipse.wst.validation.internal.ProjectUnavailableError; -import org.eclipse.wst.validation.internal.ValManager; -import org.eclipse.wst.validation.internal.ValOperation; -import org.eclipse.wst.validation.internal.ValPrefManagerGlobal; -import org.eclipse.wst.validation.internal.ValPrefManagerProject; -import org.eclipse.wst.validation.internal.ValType; -import org.eclipse.wst.validation.internal.ValidationRunner; -import org.eclipse.wst.validation.internal.ValidatorMetaData; -import org.eclipse.wst.validation.internal.ValidatorMutable; -import org.eclipse.wst.validation.internal.ValManager.UseProjectPreferences; -import org.eclipse.wst.validation.internal.model.GlobalPreferences; -import org.eclipse.wst.validation.internal.model.GlobalPreferencesValues; -import org.eclipse.wst.validation.internal.model.ProjectPreferences; -import org.eclipse.wst.validation.internal.operations.ValidationBuilder; -import org.eclipse.wst.validation.internal.operations.ValidatorManager; -import org.eclipse.wst.validation.internal.operations.WorkbenchReporter; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; - - -/** - * The central class of the Validation Framework. - * <p> - * This is a singleton class that is accessed through the getDefault() method. - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @author karasiuk - * - */ -public final class ValidationFramework { - - private volatile IDependencyIndex _dependencyIndex; - private IPerformanceMonitor _performanceMonitor; - - private Set<IProject> _suspendedProjects; - private boolean _suspendAllValidation; - - /** - * Answer the singleton, default instance of this class. - */ - public static ValidationFramework getDefault(){ - return Singleton.vf; - } - - private ValidationFramework(){} - - /** - * Add the validation builder to the project, so that the project can support - * build time validation. It is safe to call this method, if the builder was - * previously added to the project. It will not be added more than once. - * - * @param project The project that the builder is added to. - */ - public void addValidationBuilder(IProject project){ - ValidatorManager.addProjectBuildValidationSupport(project); - } - - /** - * Clear any validation markers that may have been set by this validator. - * - * @param resource - * The resource that may have it's markers cleared. - * @param validatorId - * The id of validator that created the marker. - */ - public void clearMessages(IResource resource, String validatorId) throws CoreException { - Validator v = getValidator(validatorId, null); - if (v != null)MarkerManager.getDefault().clearMarker(resource, v); - } - - /** - * Disable all validation for the given resource. This method instructs - * the framework to not run any validators on the given resource or any of - * it's children. This setting is persistent. Currently this only works with version 2 - * validators. - * <p> - * Use the enableValidation method to restore validation. - * </p> - * - * @param resource - * The resource that is having validation disabled. It must be an IFolder or an IFile. - * - * @see #enableValidation(IResource) - */ - public void disableValidation(IResource resource){ - assert resource != null; - DisabledResourceManager.getDefault().disableValidation(resource); - } - - /** - * Enable validation for the given resource. If the resource was not - * previously disabled this method call has no effect. Currently this only - * works with version 2 validators. - * - * @param resource - * The resource that is having validation re-enabled. - * - * @see #disableValidation(IResource) - */ - public void enableValidation(IResource resource){ - DisabledResourceManager.getDefault().enableValidation(resource); - } - - /** - * Answer the dependency index. Validators can use this to determine which resources depend on which - * other resources. - */ - public IDependencyIndex getDependencyIndex(){ - // note how the _dependencyIndex is volatile so that this double checking approach can be used. - if (_dependencyIndex == null){ - synchronized(this){ - if (_dependencyIndex == null)_dependencyIndex = new DependencyIndex(); - } - } - return _dependencyIndex; - } - - /** - * Answer a performance monitor for the validators. - */ - public synchronized IPerformanceMonitor getPerformanceMonitor(){ - if (_performanceMonitor == null){ - boolean traceTimes = Misc.debugOptionAsBoolean(DebugConstants.TraceTimes); - String traceFile = Platform.getDebugOption(DebugConstants.TraceTimesFile); - boolean useDoubles = Misc.debugOptionAsBoolean(DebugConstants.TraceTimesUseDoubles); - - _performanceMonitor = PerformanceMonitor.create(traceTimes, traceFile, useDoubles); - } - return _performanceMonitor; - } - - /** - * Answer the preference store that holds the persisted global validation settings. - */ - public IEclipsePreferences getPreferenceStore(){ - return new InstanceScope().getNode(ValidationPlugin.PLUGIN_ID); - } - - public IReporter getReporter(IProject project, IProgressMonitor monitor){ - return new WorkbenchReporter(project, monitor); - } - - /** - * Answer all the validators that are applicable for the given resource. A validator is - * still returned even if it has been turned off by the user. - * <p> - * The caller may still need to test if the validator has been turned off by - * the user, by using the isBuildValidation() and isManualValidation() - * methods. - * </p> - * - * @param resource - * The resource that determines which validators are applicable. - * - * @param isManual - * If true then the validator must be turned on for manual validation. - * If false then the isManualValidation setting isn't used to filter - * out validators. - * - * @param isBuild - * If true then the validator must be turned on for build based - * validation. If false then the isBuildValidation setting isn't used - * to filter out validators. - * - * @see Validator#isBuildValidation() - * @see Validator#isManualValidation() - */ - public Validator[] getValidatorsFor(IResource resource, boolean isManual, boolean isBuild){ - IProject project = resource.getProject(); - List<Validator> list = new LinkedList<Validator>(); - ContentTypeWrapper ctw = new ContentTypeWrapper(); - for (Validator val : ValManager.getDefault().getValidators(project)){ - if (val.shouldValidate(resource, isManual, isBuild, ctw))list.add(val); - } - - Validator[] result = new Validator[list.size()]; - list.toArray(result); - return result; - } - - /** - * Answer all the validators that should not validate the resource, either - * because their filters don't support the resource, or the validator has - * been disabled for both build validation and manual validation. - * - * @param resource - * The resource this is being tested. - */ - public Set<Validator> getDisabledValidatorsFor(IResource resource){ - return DisabledValidatorManager.getDefault().getDisabledValidatorsFor(resource); - } - - /** - * Answer the global validator with the given id. - * - * @deprecated Use getValidator(String id, IProject project) with a null project instead. - * - * @param id - * @return null if the validator is not found - */ - public Validator getValidator(String id){ - return ValManager.getDefault().getValidatorWithId(id, null); - } - - /** - * Answer the validator with the given id that is in effect for the given - * project. - * <p> - * Individual projects may override the global validation preference - * settings. If this is allowed and if the project has it's own settings, - * then those validators are returned via this method. - * </p> - * <p> - * The following approach is used. For version 1 validators, the validator - * is only returned if it is defined to operate on this project type. This - * is the way that the previous version of the framework did it. For version - * 2 validators, they are all returned. - * </p> - * - * @param id - * Validator id. - * @param project - * This can be null, in which case all the registered validators are - * checked. - * @return null if the validator is not found - */ - public Validator getValidator(String id, IProject project){ - return ValManager.getDefault().getValidatorWithId(id, project); - } - - /** - * Answer copies of all the registered validators. - * - * @return Answer an empty array if there are no validators. - */ - public Validator[] getValidators(){ - return ValManager.getDefault().getValidatorsCopy(); - } - - /** - * Answer the validation settings that have been defined on the - * project. To "activate" any changes to these settings, the - * {@link #applyChanges(MutableProjectSettings, boolean)} method needs to be - * called. - * - * @param project The project who's settings you wish to examine or change. - * @return Validation settings that apply to the given project. - */ - public MutableProjectSettings getProjectSettings(IProject project){ - ProjectPreferences pp = ValManager.getDefault().getProjectPreferences(project); - Validator[] vals = pp.getValidators(); - ValidatorMutable[] vms = new ValidatorMutable[vals.length]; - for (int i=0; i<vals.length; i++)vms[i] = new ValidatorMutable(vals[i]); - - MutableProjectSettings mps = new MutableProjectSettings(project, vms); - mps.setOverride(pp.getOverride()); - mps.setSuspend(pp.getSuspend()); - return mps; - } - - /** - * Answer the validation settings that have been defined at the workspace level. - * To "activate" any changes to these settings, the - * {@link #applyChanges(MutableWorkspaceSettings, boolean)} method needs to be - * called. - * - * @return Validation settings that apply to the entire workspace. - */ - public MutableWorkspaceSettings getWorkspaceSettings() throws InvocationTargetException{ - - ValManager vm = ValManager.getDefault(); - GlobalPreferences gp = vm.getGlobalPreferences(); - - Validator[] vals = vm.getValidators(); - ValidatorMutable[] vms = new ValidatorMutable[vals.length]; - for (int i=0; i<vals.length; i++)vms[i] = new ValidatorMutable(vals[i]); - - MutableWorkspaceSettings mws = new MutableWorkspaceSettings(vms, gp.asValues()); - return mws; - } - - /** - * Apply the changes that have been been to the validation settings. - * - * @param settings - * The project settings. - * @param persist - * If true then the changes are persisted to the property files. - * If false the changes are applied to the validators, but are - * not persisted. - */ - public void applyChanges(MutableProjectSettings settings, boolean persist){ - ValPrefManagerProject vpm = new ValPrefManagerProject(settings.getProject()); - vpm.savePreferences(settings, persist); - } - - /** - * Apply the changes that have been been to the validation settings. - * - * @param settings - * The workspace settings. - * @param persist - * If true then the changes are persisted to the property files. - * If false the changes are applied to the validators, but are - * not persisted. - */ - public void applyChanges(MutableWorkspaceSettings settings, boolean persist){ - - ValManager vm = ValManager.getDefault(); - GlobalPreferencesValues gpv = settings.getGlobalPreferencesValues(); - vm.replace(gpv); - - IMutableValidator[] mvs = settings.getValidators(); - ValidatorMutable[] vals = new ValidatorMutable[mvs.length]; - for (int i=0; i<mvs.length; i++)vals[i] = (ValidatorMutable)mvs[i]; - ValPrefManagerGlobal.getDefault().savePreferences(vm.getGlobalPreferences(), vals, persist); - ValPrefManagerGlobal.saveV1Preferences(vals, persist); - } - - /** - * Validators can use project level settings (Project natures and facets) to - * determine if they are applicable to the project or not. - * - * @param project - * The project that the configuration is based on. - * @return The copies of the validators that are configured to run on this project based - * on the project level settings. - * @throws ProjectUnavailableError - */ - public Validator[] getValidatorsConfiguredForProject(IProject project) throws ProjectUnavailableError { - Validator[] orig = ValManager.getDefault().getValidatorsConfiguredForProject(project, UseProjectPreferences.Normal); - Validator[] copy = new Validator[orig.length]; - for (int i=0; i<orig.length; i++)copy[i] = orig[i].copy(); - return copy; - } - - /** - * Answer all the validators that are applicable for the given resource. - * - * @param resource the resource that determines which validators are applicable. - */ - public Validator[] getValidatorsFor(IResource resource){ - List<Validator> list = new LinkedList<Validator>(); - for (Validator v : getValidatorsFor(resource, false, false)){ - if (v.isBuildValidation() || v.isManualValidation())list.add(v); - } - Validator[] vals = new Validator[list.size()]; - return list.toArray(vals); - } - - /** - * Answer true if the resource has any enabled validators. - * - * @param resource - * A file, folder or project. - * - * @param isManual - * If true then the validator must be turned on for manual validation. - * If false then the isManualValidation setting isn't used to filter - * out validators. - * - * @param isBuild - * If true then the validator must be turned on for build based - * validation. If false then the isBuildValidation setting isn't used - * to filter out validators. - */ - public boolean hasValidators(IResource resource, boolean isManual, boolean isBuild){ - return ValManager.getDefault().hasValidators(resource, isManual, isBuild); - } - - /** - * Answer whether or not the validator has been activated, i.e. has the - * bundle that defines the validator been loaded. We do not want to cause - * unnecessary bundle loading, so this check can be performed by third party - * callers, to prevent making other calls that will force the validator to - * be loaded. - * - * @param validator - * The validator that is being tested. - * @return true if the validator has already been loaded. - */ - public boolean isLoaded(Validator validator){ - return validator.isLoaded(); - } - - /** - * Waits until all validation jobs are finished. This method will block the - * calling thread until all such jobs have finished executing, or until this - * thread is interrupted. If there are no validation jobs that are - * currently waiting, running, or sleeping, this method returns immediately. - * Feedback on how the join is progressing is provided to the progress - * monitor. - * <p> - * If this method is called while the job manager is suspended, only jobs - * that are currently running will be joined. Once there are no jobs in the - * family in the {@link Job#RUNNING} state, this method returns. - * </p> - * <p> - * Note that there is a deadlock risk when using join. If the calling thread - * owns a lock or object monitor that the joined thread is waiting for, - * deadlock will occur. This method can also result in starvation of the - * current thread if another thread continues to add jobs of the given - * family, or if a job in the given family reschedules itself in an infinite - * loop. - * </p> - * - * @param monitor - * Progress monitor for reporting progress on how the wait is - * progressing, or <code>null</code> if no progress monitoring is - * required. - * @exception InterruptedException - * if this thread is interrupted while waiting - * @exception OperationCanceledException - * if the progress monitor is canceled while waiting - */ - public void join(IProgressMonitor monitor) throws InterruptedException, OperationCanceledException { - Job.getJobManager().join(ResourcesPlugin.FAMILY_AUTO_BUILD, monitor); - Job.getJobManager().join(ValidationBuilder.FAMILY_VALIDATION_JOB, monitor); - } - - /** - * Suspends, or undoes the suspension of, validation on the current project. - * If <b>suspend</b> is true then validation is suspended and if it's false - * then validation is not suspended on the project. The value of this - * variable is not persisted. - * <p> - * Be <b>very careful</b> when you use this method! Turn validation back on in a - * finally block because if the code which suspended validation crashes, the - * user has no way to reset the suspension. The user will have to shut down - * and restart the workbench to get validation to work again. - * </p> - * - * @param project - * The project that is to be suspended or unsuspended. - * @param suspend - * If true, validation on the project will be suspend. If false it will - * not be suspended. - */ - public void suspendValidation(IProject project, boolean suspend) { - if (project == null)return; - if (suspend)getSuspendedProjects().add(project); - else getSuspendedProjects().remove(project); - } - - private synchronized Set<IProject> getSuspendedProjects(){ - if (_suspendedProjects == null)_suspendedProjects = Collections.synchronizedSet(new HashSet<IProject>(20)); - return _suspendedProjects; - } - - /** - * Save the validators settings into the persistent store, there by making their settings the active settings. - * <p> - * A common use of this method would be to change whether particular validators are enabled or not. For example - * if you only wanted the JSP validator enabled, you could use code similar to this: - * <pre> - * ValidationFramework vf = ValidationFramework.getDefault(); - * Validator[] vals = vf.getValidators(); - * for (Validator v : vals){ - * boolean enabled = false; - * if (v.getValidatorClassname().equals("org.eclipse.jst.jsp.core.internal.validation.JSPBatchValidator"))enabled = true; - * v.setBuildValidation(enabled); - * v.setManualValidation(enabled); - * } - * vf.saveValidators(vals); - * </pre> - * </p> - * - * @param validators The validators that you are saving. - * - * @throws InvocationTargetException - */ - public void saveValidators(Validator[] validators) throws InvocationTargetException{ - - - ValPrefManagerGlobal gp = ValPrefManagerGlobal.getDefault(); - gp.saveAsPrefs(validators); - - GlobalConfiguration gc = ConfigurationManager.getManager().getGlobalConfiguration(); - - List<ValidatorMetaData> manual = new LinkedList<ValidatorMetaData>(); - List<ValidatorMetaData> build = new LinkedList<ValidatorMetaData>(); - for (Validator v : validators){ - V1 v1 = v.asV1Validator(); - if (v1 == null)continue; - if (v1.isManualValidation())manual.add(v1.getVmd()); - if (v1.isBuildValidation())build.add(v1.getVmd()); - } - - ValidatorMetaData[] array = new ValidatorMetaData[manual.size()]; - gc.setEnabledManualValidators(manual.toArray(array)); - - array = new ValidatorMetaData[build.size()]; - gc.setEnabledBuildValidators(build.toArray(array)); - - gc.passivate(); - gc.store(); - } - - /** - * Suspends, or undoes the suspension of, validation on all projects in the - * workbench. If "suspend" is true then validation is suspended and if it's - * "false" then validation is not suspended. The value of this variable is - * not persisted. - * <p> - * Be <b>very careful</b> when you use this method! Turn validation back on in a - * finally block because if the code which suspended validation crashes, the - * user has no way to reset the suspension. The user will have to shut down - * and restart the workbench to get validation to work again. - * </p> - */ - public void suspendAllValidation(boolean suspend) { - _suspendAllValidation = suspend; - } - - /** - * Return true if "suspend all" is enabled, false otherwise. - */ - public boolean isSuspended() { - return _suspendAllValidation; - } - - /** - * Returns true if validation will not run on the project because it's been suspended. This - * method checks only the suspension status; if validation cannot run for some other reason (for - * example, there are no enabled validators), yet the IProject is not suspended, this method - * will return true even though validation will not run. - */ - public boolean isSuspended(IProject project) { - if (_suspendAllValidation)return true; - if (project == null)return false; - return getSuspendedProjects().contains(project); - } - - /** - * This method should be called by any code that is preparing to suspend validation on a - * project. Rather than calling isSuspended(IProject), which will also return true if all validation - * has been suspended. - * - * @param project the project that is being tested - * @return boolean true if the project has been suspended - */ - public boolean isProjectSuspended(IProject project) { - if (project == null)return false; - return getSuspendedProjects().contains(project); - } - - /** - * Validate the projects. Exactly one of isManual or isBuild needs to be true. - * - * @param projects - * The projects to be validated. - * - * @param isManual - * Is this being done as part of a manual validation? i.e. did - * the user select the Validate menu item? - * - * @param isBuild - * Is this being done as part of a build? - * - * @param monitor - * - * @return the validation result which is the combined result for all the - * resources that were validated. - */ - public ValidationResults validate(IProject[] projects, final boolean isManual, final boolean isBuild, - IProgressMonitor monitor) throws CoreException{ - ValType type = ValType.Build; - if (isManual)type = ValType.Manual; - ValOperation vo = ValidationRunner.validate(createMap(projects), type, monitor, true); - return vo.getResults(); - } - - /** - * Validate a specific file resource. - * - * @param file - * The file to be validated. - * @param monitor - * Progress monitor. - * @return the result of validating the file. - */ - public ValidationResults validate(IFile file, IProgressMonitor monitor) throws CoreException{ - ValOperation vo = ValidationRunner.validate(file, ValType.Manual, monitor, true); - return vo.getResults(); - } - - /** - * Answer all the resources in the projects as a map. - * @param projects - */ - private Map<IProject, Set<IResource>> createMap(IProject[] projects) throws CoreException{ - final HashMap<IProject, Set<IResource>> map = new HashMap<IProject, Set<IResource>>(1000); - - for (IProject p : projects){ - Set<IResource> set = new HashSet<IResource>(1000); - ResourceAdder ra = new ResourceAdder(set); - p.accept(ra); - map.put(p, set); - } - return map; - } - - public static class ResourceAdder implements IResourceVisitor { - - private Set<IResource> _set; - - /** - * A class that knows how to add resources to a set. - * @param set the set where the resources are added. - */ - public ResourceAdder(Set<IResource> set){ - _set = set; - } - - public boolean visit(IResource resource) throws CoreException { - // [225839] the older validators only expect files and folders. - int type = resource.getType(); - if (type == IResource.FILE || type == IResource.FOLDER)_set.add(resource); - return true; - } - - } - - /** - * Store the singleton for the ValidationFramework. This approach is used to avoid having to synchronize the - * ValidationFramework.getDefault() method. - * - * @author karasiuk - * - */ - private static class Singleton { - static ValidationFramework vf = new ValidationFramework(); - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResult.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResult.java deleted file mode 100644 index c1714e1df..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResult.java +++ /dev/null @@ -1,385 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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.wst.validation; - -import java.util.LinkedList; -import java.util.List; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.wst.validation.internal.core.ValidationException; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; - -/** - * The result of running a validate operation. Validators create and return this objects as part of - * performing their validation. - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @author karasiuk - * - */ -public final class ValidationResult { - - private final List<ValidatorMessage> _messages = new LinkedList<ValidatorMessage>(); - - private final static ValidatorMessage[] _noMessages = new ValidatorMessage[0]; - - private boolean _canceled; - - /** - * The resources that the validated resource depends on. This can be left null. - * For example, an XML file may depend on a XSD in order to know if it is valid or not. - * It would pass back the XSD file. - */ - private IResource[] _dependsOn; - - /** - * The objects that you validated as a side effect of validating this object. The framework will not - * call you with any of these objects (in this validation run). This can be left null. - */ - private IResource[] _validated; - - private int _severityError; - private int _severityWarning; - private int _severityInfo; - - private IProject _suspendValidation; - - /** A count of the number of resources that were validated. */ - private int _numberOfValidatedResources = 1; - - private ReporterHelper _reporter; - private ValidationException _validationException; - - /** - * This is an optional method, that a validator can use to return error - * messages. The validation framework converts these into IMarkers. - * <p> - * The scenario that motivated this method, is when a validator is used both - * for <b>as you type</b> validation and <b>build</b> validation. When - * called in as you type mode, the validator doesn't want to directly create IMarkers, - * because the resource hasn't been saved yet. It needs to return something - * other than an IMarker. But when called in build mode, it does ultimately - * want IMarkers. By returning ValidatorMessages, it only needs to return - * one type of message, and those messages can be either be directly used by - * the caller, or automatically converted into IMarkers by the validation - * framework. - * </p> - * <p> - * To make matters even more complicated there is a third way to return - * messages. To make it easier for old validators to port to the new - * framework, they can continue to use an IReporter. If a validator calls - * the getReporter() method then it is assumed by the framework that that is - * the approach that they have chosen. - * </p> - * - * @see #getReporter(IProgressMonitor) - * - * @param message - * A validation message. - */ - public void add(ValidatorMessage message){ - _messages.add(message); - } - - /** - * Answer an IReporter for handing error messages. - * <p> - * This is a transition method, to help old validators port to the new validation framework. If this method - * is called it is assumed by the framework, that this IReporter will be used as the only way of passing messages - * back to the framework. - * - * @see #add(ValidatorMessage) - * @param monitor - */ - public IReporter getReporter(IProgressMonitor monitor){ - if (_reporter == null)_reporter = new ReporterHelper(monitor); - return _reporter; - } - - ReporterHelper getReporterHelper(){ - return _reporter; - } - - /** - * Merge the message counts and messages from an individual validator into this result. - * @param result it can be null, in which case it is ignored. - */ - public void mergeResults(ValidationResult result){ - if (result == null)return; - - ValidatorMessage[] msgs = result.getMessages(); - for (ValidatorMessage m : msgs){ - add(m); - int severity = m.getAttribute(IMarker.SEVERITY, 0); - switch (severity){ - case IMarker.SEVERITY_ERROR: - incrementError(1); - break; - case IMarker.SEVERITY_WARNING: - incrementWarning(1); - break; - case IMarker.SEVERITY_INFO: - incrementInfo(1); - break; - - } - } - - incrementError(result.getSeverityError()); - incrementWarning(result.getSeverityWarning()); - incrementInfo(result.getSeverityInfo()); - - _numberOfValidatedResources += result.getNumberOfValidatedResources(); - - } - - /** - * Answer the resources that the validated resource depends on. - */ - public IResource[] getDependsOn() { - return _dependsOn; - } - - /** - * Answer any validation messages that were added by the validator. - * @return an array is returned even if there are no messages. - */ - public ValidatorMessage[] getMessages(){ - if (_messages == null)return _noMessages; - ValidatorMessage[] msgs = new ValidatorMessage[_messages.size()]; - _messages.toArray(msgs); - return msgs; - } - - /** - * Answer a copy of any validation messages that were added by the validator. The array is a new - * array, and each message is a copy. - * @return an array is returned even if there are no messages. - */ - public synchronized ValidatorMessage[] getMessagesAsCopy(){ - if (_messages == null)return _noMessages; - ValidatorMessage[] msgs = new ValidatorMessage[_messages.size()]; - int i = 0; - for (ValidatorMessage msg : _messages)msgs[i++] = msg.asCopy(); - return msgs; - } - - /** - * Update the resources that the validated resource depends on. This can be - * left null. For example, a XML file may depend on a XSD file in order to - * know if it is valid or not. It would pass back that XSD file. - * - * @param dependsOn - * If this is null then the dependency information is not updated. To - * remove the dependency information, an empty array needs to be - * supplied. A non null parameter, <b>replaces</b> all the dependency - * information for this resource, for this validator. - */ - public void setDependsOn(IResource[] dependsOn) { - _dependsOn = dependsOn; - } - - /** - * @return All the resources that were validated as a side-effect of - * validating the main resource, or null if none were. - */ - public IResource[] getValidated() { - return _validated; - } - - /** - * Indicate that additional resources have been validated as part of this - * validate operation. Sometimes in the course of performing a validation on - * one resource it is necessary to validate other resources as well. This - * method is used to let the framework know about these additional validated - * resources, to possibly save them being validated redundantly. - * - * @param validated - * Any additional resources that were validated. - */ - public void setValidated(IResource[] validated) { - _validated = validated; - } - - /** - * Answer the number of error messages that were generated as part of this validation operation. - */ - public int getSeverityError() { - return _severityError; - } - - /** - * Set the number of error messages that were generated as part of this validation operation. - * <p> - * Messages added through the add(ValidationMessage) method should not be included here, as this - * information will be determined from the ValidationMessage. - * </p> - */ - public void setSeverityError(int severityError) { - _severityError = severityError; - } - - - /** - * Increment the number of error messages that were generated as part of this validation operation. - * <p> - * Messages added through the add(ValidationMessage) method should not be included here, as this - * information will be determined from the ValidationMessage. - * </p> - * - * @return the current number of errors. - */ - public int incrementError(int errors){ - _severityError += errors; - return _severityError; - } - - /** - * Answer the number of warning messages that were generated as part of this validation operation. - */ - public int getSeverityWarning() { - return _severityWarning; - } - - /** - * Set the number of warning messages that were generated as part of this validation operation. - * <p> - * Messages added through the add(ValidationMessage) method should not be included here, as this - * information will be determined from the ValidationMessage. - * </p> - */ - public void setSeverityWarning(int severityWarning) { - _severityWarning = severityWarning; - } - - /** - * Increment the number of warning messages that were generated as part of this validation operation. - * <p> - * Messages added through the add(ValidationMessage) method should not be included here, as this - * information will be determined from the ValidationMessage. - * </p> - * - * @return the current number of warnings. - */ - public int incrementWarning(int warnings){ - _severityWarning += warnings; - return _severityWarning; - } - - /** - * Answer the number of informational messages that were generated as part of this validation operation. - */ - public int getSeverityInfo() { - return _severityInfo; - } - - /** - * Set the number of informational messages that were generated as part of this validation operation. - * <p> - * Messages added through the add(ValidationMessage) method should not be included here, as this - * information will be determined from the ValidationMessage. - * </p> - */ - public void setSeverityInfo(int severityInfo) { - _severityInfo = severityInfo; - } - - /** - * Increment the number of informational messages that were generated as part of this validation operation. - * <p> - * Messages added through the add(ValidationMessage) method should not be included here, as this - * information will be determined from the ValidationMessage. - * </p> - * - * @return the current number of informational message. - */ - public int incrementInfo(int info){ - _severityInfo += info; - return _severityInfo; - } - - /** - * Was the operation canceled before it completed? For example if the validation is being run through the - * user interface, the end user can cancel the operation through the progress monitor. - * - * @return true if the operation was canceled - */ - public boolean isCanceled() { - return _canceled; - } - - /** - * Indicate if the operation was canceled. - * - * @param canceled - * Set to true if it was canceled and false if it was not canceled. - */ - public void setCanceled(boolean canceled) { - _canceled = canceled; - } - - /** - * Answer the number of resources that have been validated. - */ - public int getNumberOfValidatedResources() { - if (_validated == null)return _numberOfValidatedResources; - return _numberOfValidatedResources + _validated.length; - } - - /** - * If the validation ended with an exception, answer it. - * @return null if the validator did not finish with an exception. - */ - public ValidationException getValidationException() { - return _validationException; - } - - /** - * If the validation failed with an exception, it can be recorded here. - * <p> - * This method is provided for old validators to ease their transition to the new framework. - * </p> - * @param validationException - */ - public void setValidationException(ValidationException validationException) { - _validationException = validationException; - } - - /** - * Answer the project that the validator would like to have suspended. - * - * @return the project to suspend or null. The normal result is null, which means that - * the validator wishes to receive normal validation requests. - */ - public IProject getSuspendValidation(){ - return _suspendValidation; - } - - /** - * Calling this method will inform the framework, that this validator does not wish to be - * called again for any resources in this project, for the duration of this validation operation. - * <p> - * Some validators may have a rich set of triggers, but once they have been invoked once, - * do not need to be invoked again during the course of the current validation. - * </p> - * @param project The project that this validator no longer wants to be notified on. - */ - public void setSuspendValidation(IProject project) { - _suspendValidation = project; - } -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResults.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResults.java deleted file mode 100644 index ba947f878..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationResults.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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.wst.validation; - - -/** - * The combined results of validating multiple resources. - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @author karasiuk - * - */ -public final class ValidationResults { - - private final ValidatorMessage[] _messages; - private final int _error; - private final int _warn; - private final int _info; - - public ValidationResults(ValidationResult result){ - if (result == null){ - _messages = new ValidatorMessage[0]; - _error = 0; - _warn = 0; - _info = 0; - } - else { - _messages = result.getMessagesAsCopy(); - _error = result.getSeverityError(); - _warn = result.getSeverityWarning(); - _info = result.getSeverityInfo(); - } - } - - /** - * Answer any validation messages that were added by the validation operation. - * @return an array is returned even if there are no messages. - */ - public ValidatorMessage[] getMessages(){ - return _messages; - } - - /** - * Answer the number of error messages that were generated as part of this validation operation. - */ - public int getSeverityError() { - return _error; - } - - /** - * Answer the number of informational messages that were generated as part of this validation operation. - */ - public int getSeverityInfo() { - return _info; - } - - /** - * Answer the number of warning messages that were generated as part of this validation operation. - */ - public int getSeverityWarning() { - return _warn; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationState.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationState.java deleted file mode 100644 index 8097de468..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidationState.java +++ /dev/null @@ -1,90 +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.wst.validation; - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -/** - * Keep track of arbitrary validation data, during the course of a validation. - * <p> - * To enable more efficient caching, the validation framework, allows individual validators to cache - * arbitrary data during the validation process. Use of this object is completely optional. - * <p> - * Since some validators wish to share data with other validators, any validator can see the state data for - * any other validator, since the id is simply the validator's extension id. - * <p> - * This object is freed at the end of the validation process. - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that is still under development and expected to - * change significantly before reaching stability. It is being made available at this early stage to solicit feedback - * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken - * (repeatedly) as the API evolves. - * </p> - * @noextend - * @author karasiuk - * - */ -public final class ValidationState { - - /** - * This is a special id. - * <p> - * If a resource that is depended on by others is changed, then the - * dependent resources are validated. The depended on resource, which is the - * resource that actually changed, is placed into the ValidationState using - * this id. - * </p> - * @deprecated This approach is not thread safe, the longer form of the AbstractValidator validate method should be used instead. - * @see AbstractValidator#validate(ValidationEvent, ValidationState, org.eclipse.core.runtime.IProgressMonitor) - */ - public static final String TriggerResource = ValidationPlugin.PLUGIN_ID + ".Trigger"; //$NON-NLS-1$ - - // I can't use a ConncurrentHashMap because some of the clients store nulls. - private final Map<String, Object> _map = new HashMap<String, Object>(50); - - public ValidationState(){ - } - - /** - * Save some state information. - * - * @param id - * By convention this is the fully qualified validator extension id. - * For example: org.eclipse.wst.html.ui.HTMLValidator - * - * @param value - * Any arbitrary data that the validator might find useful. The - * validation framework doesn't do anything with this object except - * pass it along during the validation process. - */ - public synchronized void put(String id, Object value){ - _map.put(id, value); - } - - /** - * Answer the state data for the given validator. - * - * @param id - * By convention this is the fully qualified validator extension point - * id. For example org.eclipse.wst.html.ui.HTMLValidator - * - * @return any arbitrary data that the validator might find useful, - * including null. - */ - public synchronized Object get(String id){ - return _map.get(id); - } - - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Validator.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Validator.java deleted file mode 100644 index 69bb8835a..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/Validator.java +++ /dev/null @@ -1,1356 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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.wst.validation; - -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IContributor; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Platform; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.validation.internal.ConfigurationConstants; -import org.eclipse.wst.validation.internal.ConfigurationManager; -import org.eclipse.wst.validation.internal.ContentTypeWrapper; -import org.eclipse.wst.validation.internal.ExtensionConstants; -import org.eclipse.wst.validation.internal.MarkerManager; -import org.eclipse.wst.validation.internal.Misc; -import org.eclipse.wst.validation.internal.NullValidator; -import org.eclipse.wst.validation.internal.SummaryReporter; -import org.eclipse.wst.validation.internal.Tracing; -import org.eclipse.wst.validation.internal.ValManager; -import org.eclipse.wst.validation.internal.ValMessages; -import org.eclipse.wst.validation.internal.ValOperation; -import org.eclipse.wst.validation.internal.ValPrefManagerGlobal; -import org.eclipse.wst.validation.internal.ValPrefManagerProject; -import org.eclipse.wst.validation.internal.ValType; -import org.eclipse.wst.validation.internal.ValidationConfiguration; -import org.eclipse.wst.validation.internal.ValidatorExtensionReader; -import org.eclipse.wst.validation.internal.ValidatorMetaData; -import org.eclipse.wst.validation.internal.core.ValidatorLauncher; -import org.eclipse.wst.validation.internal.delegates.ValidatorDelegateDescriptor; -import org.eclipse.wst.validation.internal.delegates.ValidatorDelegatesRegistry; -import org.eclipse.wst.validation.internal.model.FilterGroup; -import org.eclipse.wst.validation.internal.operations.IWorkbenchContext; -import org.eclipse.wst.validation.internal.operations.WorkbenchContext; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; - -/** - * Represents a validator. This gets instantiated through one of the validator extension points. - * <p> - * <b>This class is not API</b>. - * </p> - * - * @author karasiuk - * - */ -public abstract class Validator implements Comparable<Validator> { - // Remember if you add a new instance variable, make sure that you update the copy and become methods - - /** - * The level of configuration for the validator. - * <ul> - * <li>Extension - Defined by an extension point.</li> - * <li>Global - Defined by a global preference.</li> - * <li>Project - Defined by a project property.</li> - * </ul> - */ - public enum Level {Extension, Global, Project}; - - protected boolean _buildValidation = true; - - /** If this is a delegating validator, then this field holds the validator that will be delegated to. */ - private String _delegatingId; - - /** - * If this validator is also used to control an ISource validator, the id of the ISource validator is - * registered here. - */ - private String _sourceId; - - protected boolean _manualValidation = true; - - /** An optional customized marker id for this validator. */ - private String _markerId; - - /** - * Version of the filter definition. By increasing this number the framework can know that a plug-in has - * changed it's filters. - */ - private int _version = 1; - - /** Map simple message id's to message settings. */ - private Map<String, MessageSeveritySetting> _messageSettings; - - /** The project that you are defined in. This can be null which means that you are a global validator. */ - protected IProject _project; - - /** How many times has a global field in this validator been changed since it was created (or copied)? */ - protected transient int _changeCountGlobal; - - /** How many times has a message field in this validator been changed since it was created (or copied)? */ - protected transient int _changeCountMessages; - - /** Has the validator been migrated from an earlier version in this session, but not yet saved? */ - private boolean _migrated; - - public Validator(IProject project){ - _project = project; - } - - void setMigrated(boolean migrated){ - _migrated = migrated; - } - - /** - * Create a new validator based on a abstract validator. - * - * @param validator - * The validator that is being wrapped. - * - * @param project - * The project that you are defined in. This can be null which - * means that you are a global validator. - */ - public static Validator create(IConfigurationElement validator, IProject project) { - V2 v2 = new V2(validator, project); - return v2; - } - - /** - * Create a new validator based on validator meta data. - * - * @param project - * The project that you are defined in. This can be null which - * means that you are a global validator. - */ - public static Validator create(ValidatorMetaData vmd, ValidationConfiguration config, IProject project){ - V1 v1 = new V1(vmd, config, project); - return v1; - } - - /** - * If you are a version 1 validator, answer yourself as one, otherwise answer null. - */ - public V1 asV1Validator(){ - return null; - } - - /** - * If you are a version 2 validator, answer yourself as one, otherwise answer null. - */ - public V2 asV2Validator() { - return null; - } - - /** - * The project is being cleaned, this method gives the validator a chance to do any special cleanup. - * The default is to do nothing. - * - * @param project the project being built. - * @param monitor the monitor that should be used for reporting progress if the clean takes a long time. - */ - public void clean(IProject project, ValOperation operation, IProgressMonitor monitor){ - } - - /** - * Compare yourself based on Validator name. - */ - public int compareTo(Validator validator) { - return getName().compareTo(validator.getName()); - } - - /** Answer a deep copy of yourself. */ - public Validator copy(){ - return copy(false); - } - - public abstract Validator copy(boolean includeChangeCounts); - - /** - * Update your direct, non transient fields from the fields in v. - */ - protected void copyLocal(Validator v, boolean includeChangeCounts){ - _buildValidation = v._buildValidation; - _delegatingId = v._delegatingId; - _manualValidation = v._manualValidation; - _markerId = v._markerId; - _messageSettings = v._messageSettings; - _sourceId = v._sourceId; - _version = v._version; - _migrated = v._migrated; - - if (includeChangeCounts){ - _changeCountGlobal = v._changeCountGlobal; - _changeCountMessages = v._changeCountMessages; - } - } - - /** - * Should the validation framework first clear the markers that this - * validator has placed on this resource? This method can be overridden by - * validator implementors to provide a validator specific behavior. - * - * @param event - * The validation event that triggered the validation. - * @return true if the validation framework should first clear all the - * markers that this validator produced. This is the default - * behavior. Return false to leave the markers unchanged. It then - * becomes the responsibility of the validator to manage it's own - * markers for this resource, for this validation event. - */ - public boolean shouldClearMarkers(ValidationEvent event){ - return true; - } - - /** - * Answer true if this validator, based on it's filters, should validate - * this resource. This method does not check to see if global validation or - * project validation has been suspended or not. - * - * @param resource - * The resource to be checked. - * @param isManual - * If true then this validator must also be enabled for manual - * validation. - * @param isBuild - * If true then this validator must also be enabled for builder - * based validation. - * - * @return true if the resource should be validated. - */ - public boolean shouldValidate(IResource resource, boolean isManual, boolean isBuild){ - return shouldValidate(resource, isManual, isBuild, new ContentTypeWrapper()); - } - - /** - * Answer true if this validator, based on it's filters, should validate - * this resource. This method does not check to see if global validation or - * project validation has been suspended or not. - * - * @param resource - * The resource to be checked. - * @param isManual - * If true then this validator must also be enabled for manual - * validation. - * @param isBuild - * If true then this validator must also be enabled for builder - * based validation. - * @param contentTypeWrapper - * For repeated calls on the same resource, it is more efficient - * to remember the content type. - * @return true if the resource should be validated. - * @see Friend#shouldValidate(Validator, IResource, boolean, boolean, ContentTypeWrapper) - */ - boolean shouldValidate(IResource resource, boolean isManual, boolean isBuild, - ContentTypeWrapper contentTypeWrapper){ - - if (isManual && !_manualValidation)return false; - if (isBuild && !_buildValidation)return false; - - return shouldValidate(resource, contentTypeWrapper); - } - - /** - * Answer true if this validator, based on it's filters, should validate - * this resource. This method does not check to see if global validation or - * project validation has been suspended or not. - * - * @param resource - * The resource to be checked. - * @param valType - * The context to use when performing the check. - * - * @return true if the resource should be validated. - */ - public boolean shouldValidate(IResource resource, ValType valType){ - return shouldValidate(resource, valType, new ContentTypeWrapper()); - } - - /** - * Answer true if this validator, based on it's filters, should validate - * this resource. This method does not check to see if global validation or - * project validation has been suspended or not. - * - * @param resource - * The resource to be checked. - * @param valType - * The context to use when performing the check. - * @param contentTypeWrapper - * For repeated calls on the same resource, it is more efficient - * to remember the content type. - * - * @return true if the resource should be validated. - * - * @see Friend#shouldValidate(Validator, IResource, ValType, ContentTypeWrapper) - */ - boolean shouldValidate(IResource resource, ValType valType, ContentTypeWrapper contentTypeWrapper){ - if (Tracing.matchesExtraDetail(getId())){ - Tracing.log("Validator-01: checking if " + getId() + " should validate " + resource); //$NON-NLS-1$ //$NON-NLS-2$ - } - if (valType == ValType.Manual && !_manualValidation)return false; - if (valType == ValType.Build && !_buildValidation)return false; - - boolean result = shouldValidate(resource, contentTypeWrapper); - if (Tracing.matchesExtraDetail(getId())){ - Tracing.log("Validator-02: result = " + result); //$NON-NLS-1$ - } - - return result; - } - - /** - * Answer true if this validator, based on it's filters, should validate this project. This method - * does not check to see if global validation or project validation has been suspended or not. - * - * @param project the project to be checked - * @param type The type of validation request - * - * @return true if the project should be validated. - */ - public boolean shouldValidateProject(IProject project, ValType type){ - return shouldValidateProject(project, type == ValType.Manual, type == ValType.Build); - } - - /** - * Answer true if this validator, based on it's filters, should validate this project. This method - * does not check to see if global validation or project validation has been suspended or not. - * - * @param project the project to be checked - * @param isManual if true then this validator must also be enabled for manual validation. - * @param isBuild if true then this validator must also be enabled for builder based validation. - * - * @return true if the project should be validated. - */ - public boolean shouldValidateProject(IProject project, boolean isManual, boolean isBuild){ - if (Tracing.matchesExtraDetail(getId())){ - Tracing.log("Validator-03: checking if " + getId() + " should validate " + project); //$NON-NLS-1$ //$NON-NLS-2$ - } - if (isManual && !_manualValidation)return false; - if (isBuild && !_buildValidation)return false; - if (project == null || !project.isOpen())return false; - boolean result = shouldValidateProject(project); - if (Tracing.matchesExtraDetail(getId())){ - Tracing.log("Validator-04: result " + result); //$NON-NLS-1$ - } - return result; - } - - /** - * Validate the resource. - * - * @param resource - * The resource to be validated. - * @param kind - * The kind of resource change, see IResourceDelta for values. - * @param operation - * The operation that this validation is running under. This can - * be null. - * @param monitor - * A way to report progress. This can be null. - * - * @return the result of doing the validation, it can be, but usually isn't - * null. - */ - public abstract ValidationResult validate(IResource resource, int kind, ValOperation operation, IProgressMonitor monitor); - - /** - * Validate the resource. - * - * @param resource - * The resource to be validated. - * @param kind - * The kind of resource change, see IResourceDelta for values. - * @param operation - * The operation that this validation is running under. This can - * be null. - * @param monitor - * A way to report progress. This can be null. - * @param event - * An event that describes in more detail what should be - * validated and why it should be validated. This can be null. - * - * @return the result of doing the validation, it can be, but usually isn't - * null. - */ - public ValidationResult validate(IResource resource, int kind, ValOperation operation, IProgressMonitor monitor, ValidationEvent event){ - // The reason that the resource and kind are still specified, is that I didn't want to remove a public method in the service - // stream. - return validate(resource, kind, operation, monitor); - } - - /** - * This method will be called before any validation takes place. It allows validators to perform any - * initialization that they might need. - * - * @param project the project that is being validated. For the very first call in the validation phase, - * this will be null. That is the signal to the validator that a top level validation is starting. - * Subsequently, the project will be set, as each of the individual projects are validated. - * - * @param state a way to pass arbitrary, validator specific, data from one invocation of a validator to - * the next, during the validation phase. - * - * @param monitor the monitor that should be used for reporting progress if the clean takes a long time. - */ - public void validationStarting(IProject project, ValidationState state, IProgressMonitor monitor){ - // subclasses need to override this, if they wish to let their validators know about this event - } - - /** - * This method will be called when validation is complete. It allows validators to perform any - * cleanup that they might need to do. - * - * @param project the project that was validated. The very last call in the validation will set this to - * null so that the validator knows that all the projects have now been validated. - * - * @param state a way to pass arbitrary, validator specific, data from one invocation of a validator to - * the next, during the validation phase. - * - * @param monitor the monitor that should be used for reporting progress if the clean takes a long time. - */ - public void validationFinishing(IProject project, ValidationState state, IProgressMonitor monitor){ - // subclasses need to override this, if they wish to let their validators know about this event - } - - void add(MessageSeveritySetting message){ - // I can't use getMessageSettings() here, as that will put us into an infinite loop - if (_messageSettings == null){ - _messageSettings = new HashMap<String, MessageSeveritySetting>(10); - } - _messageSettings.put(message.getId(), message); - bumpChangeCountMessages(); - } - - public IValidator asIValidator(){ - return null; - } - - protected abstract boolean shouldValidate(IResource resource, ContentTypeWrapper contentTypeWrapper); - protected abstract boolean shouldValidateProject(IProject project); - - public abstract String getId(); - - public MessageSeveritySetting getMessage(String id){ - return getMessageSettings().get(id); - } - - /** - * Answer all the message settings that this validator has defined. - * - * @return an empty map if the validator did not define any message settings. - */ - public Map<String, MessageSeveritySetting> getMessageSettings(){ - Map<String, MessageSeveritySetting> settings = _messageSettings; - if (settings == null){ - settings = new HashMap<String, MessageSeveritySetting>(10); - init(settings); - if (ValManager.getDefault().mustUseGlobalValidators(getProject())){ - ValPrefManagerGlobal gp = ValPrefManagerGlobal.getDefault(); - gp.loadMessages(this, settings); - } - else { - ValPrefManagerProject vp = new ValPrefManagerProject(getProject()); - vp.loadMessages(this, settings); - } - _messageSettings = settings; - } - return settings; - } - - /** - * Answer a hash code for the configurable fields so that we can quickly determine if two - * validators are the same. - */ - public int hashCodeForConfig(){ - int h = 0; - if (_buildValidation)h += 101; - if (_delegatingId != null)h += _delegatingId.hashCode(); - if (_manualValidation)h += 201; - if (_messageSettings != null){ - for (MessageSeveritySetting ms : _messageSettings.values())h += ms.hashCode(); - } - if (_sourceId != null)h += _sourceId.hashCode(); - h += _version; - return h; - } - - private void init(Map<String, MessageSeveritySetting> settings) { - for (MessageSeveritySetting ms : ValidatorExtensionReader.getDefault().addMessages(this)){ - settings.put(ms.getId(), ms); - } - } - - public abstract String getName(); - - /** - * Answer the project that you were enabled on. - * - * @return null if you are a global (i.e. workspace level) validator. - */ - public IProject getProject(){ - return _project; - } - - /** - * Answer the name of the class that implements the validator. - */ - public abstract String getValidatorClassname(); - - /** - * Is this validator currently enabled for validations that are triggered manually? - */ - public boolean isManualValidation() { - return _manualValidation; - } - - /** - * Set whether this validator should be triggered as part of a manual validation. - * - * @param manualValidation - * @return true if the setting changed. - */ - public boolean setManualValidation(boolean manualValidation) { - return setManualValidation2(manualValidation); - } - - protected final boolean setManualValidation2(boolean manualValidation) { - boolean changed = false; - if (_manualValidation != manualValidation){ - bumpChangeCountGlobal(); - changed = true; - _manualValidation = manualValidation; - } - return changed; - } - - /** - * Is this validator currently enabled for validations that are triggered by builds? - */ - public boolean isBuildValidation() { - return _buildValidation; - } - - /** - * Has the validator changed since it was last created or copied? Or was it migrated from an earlier version. - */ - public boolean isChanged(){ - if (_changeCountGlobal > 0 || _changeCountMessages > 0 || _migrated)return true; - return false; - } - - /** - * Has the validator's implementation been loaded yet? This is used by some test cases to ensure that - * plug-ins are not loaded too early. - */ - abstract boolean isLoaded(); - - - /** - * Set whether this validator should be triggered by the build process. - * - * @param buildValidation - * @return true if the setting changed. - */ - public boolean setBuildValidation(boolean buildValidation) { - return setBuildValidation2(buildValidation); - } - - protected final boolean setBuildValidation2(boolean buildValidation) { - boolean changed = false; - if (_buildValidation != buildValidation){ - bumpChangeCountGlobal(); - changed = true; - _buildValidation = buildValidation; - } - return changed; - } - - /** - * Get the id of the "real" validator, that is the validator that will be called when this delegating - * validator is asked to validate something. If this isn't a delegating validator answer null. - */ - public String getDelegatingId() { - return _delegatingId; - } - - /** - * Set the id of the "real" validator, that is the validator that will be called when this delegating - * validator is asked to validate something. - * - * @param delegating the id of the validator that is actually going to perform the validation. - */ - public void setDelegatingId(String delegating) { - if (!Misc.same(_delegatingId, delegating)){ - _delegatingId = delegating; - bumpChangeCountGlobal(); - } - } - - public int getVersion() { - return _version; - } - - public void setVersion(int version) { - if (_version != version){ - _version = version; - bumpChangeCountGlobal(); - } - } - - @Override - public String toString() { - return getName(); - } - -/** - * A validator that uses version 1 of the validation framework. - * @author karasiuk - * - */ -public static class V1 extends Validator { - private ValidatorMetaData _vmd; - - /** - * Create a new version 1 validator. - * @param vmd - * @param config this is used to set the global enablement options. In some case this can be null. - */ - public V1(ValidatorMetaData vmd, ValidationConfiguration config, IProject project){ - super(project); - _vmd = vmd; - if (config != null){ - setBuildValidation(config.isBuildEnabled(vmd)); - setManualValidation(config.isManualEnabled(vmd)); - } - setDelegatingId(ValidatorDelegatesRegistry.getInstance().getDefaultDelegate(_vmd.getValidatorUniqueName())); - if (_vmd.getMarkerIds() != null && _vmd.getMarkerIds().length > 0)setMarkerId(_vmd.getMarkerIds()[0]); - resetChangeCounters(); - } - - @Override - public IValidator asIValidator() { - IValidator v = null; - try { - v = _vmd.getValidator(); - } - catch (InstantiationException e){ - ValidationPlugin.getPlugin().handleException(e); - return null; - } - return v; - } - - public V1 asV1Validator() { - return this; - } - - public Validator copy(boolean includeChangeCounts) { - V1 v = new V1Copy(_vmd, null, _project); - v.copyLocal(this, includeChangeCounts); - - return v; - } - - public String getName() { - return _vmd.getValidatorDisplayName(); - } - - public ValidatorMetaData getVmd(){ - return _vmd; - } - - public String getValidatorClassname(){ - String name = ""; //$NON-NLS-1$ - try { - name = _vmd.getValidator().getClass().getName(); - } - catch (Exception e){ - // eat it - } - return name; - } - public String getId() { - return _vmd.getValidatorUniqueName(); - } - - @Override - boolean isLoaded() { - return _vmd.isActive(); - } - - @Override - public boolean setBuildValidation(boolean buildValidation) { - boolean changed = super.setBuildValidation(buildValidation); - _vmd.setBuildValidation(buildValidation); - return changed; - } - - @Override - public boolean setManualValidation(boolean manualValidation) { - boolean changed = super.setManualValidation(manualValidation); - _vmd.setManualValidation(manualValidation); - return changed; - } - - @Override - protected boolean shouldValidate(IResource resource, ContentTypeWrapper contentTypeWrapper) { - return _vmd.isApplicableTo(resource); - } - - @Override - protected boolean shouldValidateProject(IProject project) { - // TODO determine if this can be optimized - return true; - } - - @Override - public ValidationResult validate(IResource resource, int kind, ValOperation operation, - IProgressMonitor monitor) { - - if (monitor == null)monitor = new NullProgressMonitor(); - - ValidationResult vr = new ValidationResult(); - IValidator v = asIValidator(); - if (v == null)return null; - - try { - IProject project = resource.getProject(); - SummaryReporter reporter = new SummaryReporter(project, monitor); - IWorkbenchContext helper = _vmd.getHelper(project); - if (helper instanceof WorkbenchContext){ - WorkbenchContext wc = (WorkbenchContext)helper; - List<String> files = new LinkedList<String>(); - // [213631] The JSP validator expects full paths not relative paths, but the XML validator - // expects relative paths. - files.add(wc.getPortableName(resource)); - wc.setValidationFileURIs(files); - } - try { - ValidatorLauncher.getLauncher().start(helper, v, reporter); - } - finally { - try { - v.cleanup(reporter); - } - finally { - helper.cleanup(reporter); - } - } - - vr.incrementError(reporter.getSeverityHigh()); - vr.incrementWarning(reporter.getSeverityNormal()); - vr.incrementInfo(reporter.getSeverityLow()); - - } - catch (Exception e){ - ValidationPlugin.getPlugin().handleException(e); - } - return vr; - } - - /* - * GRK - Because I didn't want to try to make a true copy of the V1 validator, (because I didn't - * want to copy the vmd object), I came up with this approach to only copy the fields that - * the preference page was worried about. - */ - public final static class V1Copy extends V1 { - public V1Copy(ValidatorMetaData vmd, ValidationConfiguration vc, IProject project){ - super(vmd, vc, project); - } - - @Override - public boolean setManualValidation(boolean bool) { - return setManualValidation2(bool); - } - - @Override - public boolean setBuildValidation(boolean bool) { - return setBuildValidation2(bool); - } - - } - -} - -/** - * A validator that uses version 2 of the validation framework. - * @author karasiuk - * - */ -public final static class V2 extends Validator implements IAdaptable { - private AbstractValidator _validator; - - private List<FilterGroup> _groups = new LinkedList<FilterGroup>(); - private FilterGroup[] _groupsArray; - - /** The full id of the extension. */ - private String _id; - - /** Name of the validator. */ - private String _name; - - /** - * We don't want to create the validator too early, as it may trigger new plug-ins to be loaded. - * We delay that as long as possible, by starting with just the config element. - */ - private IConfigurationElement _validatorConfigElement; - - private String _validatorClassName; - - /** - * An array containing the validator group IDs for which this validator is a member. - */ - private String[] _validatorGroupIds; - - /** - * If this validator is a delegating validator, then this is the "real" validator (i.e. the one that - * does the work). - */ - private AbstractValidator _delegated; - - /** How many times has a group field in this validator been changed since it was created (or copied)? */ - protected transient int _changeCountGroups; - - private Level _level; - - /** - * Do we still need to invoke the validateStarting method for this validator, for the null project? - * - * Because we do not want to activate a validator's plug-in too soon, we do not activate the validator - * as a reaction to the global validation starting event. Instead we mark it pending, and wait until - * we are sure that we have something to validate. - * - * If this flag is true, it means that the validateStarting method still needs to be called for this validator. - */ - private AtomicBoolean _pendingValidationStarted = new AtomicBoolean(); - - V2(IConfigurationElement configElement, IProject project){ - super(project); - assert configElement != null; - _validatorConfigElement = configElement; - _validatorClassName = configElement.getAttribute(ExtensionConstants.AttribClass); - - IConfigurationElement[] groupReferenceElements = configElement.getChildren(ExtensionConstants.Group.elementGroup); - List<String> validatorGroupIDs = new ArrayList<String>(); - for (IConfigurationElement groupElement : groupReferenceElements) { - String id = groupElement.getAttribute(ExtensionConstants.Group.attId); - if (id != null)validatorGroupIDs.add(id); - } - _validatorGroupIds = validatorGroupIDs.toArray(new String[validatorGroupIDs.size()]); - - init(); - } - - private V2(IProject project, String validatorClassName, AbstractValidator validator){ - super(project); - assert validator != null; - - _validatorClassName = validatorClassName; - _validator = validator; - init(); - } - - private void init(){ - try { - String id = ConfigurationManager.getManager().getConfiguration(_project).getDelegateForTarget(_validatorClassName); - if (id == null) id = ValidatorDelegatesRegistry.getInstance().getDefaultDelegate(_validatorClassName); - setDelegatingId(id); - } - catch (InvocationTargetException e){ - ValidationPlugin.getPlugin().handleException(e); - } - resetChangeCounters(); - } - - public synchronized void add(FilterGroup fg) { - assert fg != null; - _groupsArray = null; - _groups.add(fg); - bumpChangeCountGroups(); - } - - @Override - public IValidator asIValidator() { - AbstractValidator av = getDelegatedValidator(); - if (av instanceof IValidator)return (IValidator)av; - return super.asIValidator(); - } - - @Override - public V2 asV2Validator() { - return this; - } - - /** - * Let the validator know that a clean is about to happen. - * - * @param project the project that is being cleaned. This can be null which means that the workspace - * is being cleaned (in which case a separate call will be made for each open project). - * - */ - @Override - public void clean(IProject project, ValOperation operation, IProgressMonitor monitor) { - getDelegatedValidator().clean(project, operation.getState(), monitor); - } - - @Override - public Validator copy(boolean includeChangeCounts) { - V2 v = null; - if (_validatorConfigElement != null)v = new V2(_validatorConfigElement, _project); - else v = new V2(_project, _validatorClassName, _validator); - v.copyLocal(this, includeChangeCounts); - - if (includeChangeCounts)v._changeCountGroups = _changeCountGroups; - - FilterGroup[] groups = getGroups(); - v._groupsArray = new FilterGroup[groups.length]; - for (int i=0; i<groups.length; i++){ - v._groupsArray[i] = groups[i]; - v._groups.add(groups[i]); - } - - v._id = _id; - v._name = _name; - v._validatorGroupIds = _validatorGroupIds; - v._pendingValidationStarted = _pendingValidationStarted; - - return v; - } - - public int getChangeCountGroups(){ - return _changeCountGroups; - } - - public void bumpChangeCountGroups(){ - _changeCountGroups++; - } - - public Level getLevel() { - return _level; - } - - public void setLevel(Level level) { - assert _level == null; - _level = level; - } - - /** - * Answer the actual validator that is going to perform the validation. If this is a normal validator this - * method will simply answer itself. However if this is a delegating validator, then this will answer the - * "real" validator. - */ - public AbstractValidator getDelegatedValidator(){ - AbstractValidator delegated = _delegated; - if (delegated != null)return delegated; - else if (getDelegatingId() == null)return getValidator(); - try { - ValidatorDelegateDescriptor vdd = ValidatorDelegatesRegistry.getInstance() - .getDescriptor(getValidatorClassname(), getDelegatingId()); - if (vdd == null)return getValidator(); - delegated = vdd.getValidator2(); - } - catch (Exception e){ - ValidationPlugin.getPlugin().handleException(e); - delegated = new NullValidator(); - } - delegated.setParent(this); - _delegated = delegated; - return delegated; - } - - @Override - public String getId() { - return _id; - } - - /** - * Answer the validator's filter groups. - * @return an empty array if the validator does not have any filter groups. - */ - public synchronized FilterGroup[] getGroups(){ - FilterGroup[] groups = _groupsArray; - if (groups == null){ - groups = new FilterGroup[_groups.size()]; - _groups.toArray(groups); - _groupsArray = groups; - } - return groups; - } - - @Override - public String getName() { - return _name; - } - - public AbstractValidator getValidator() { - if (_validator == null){ - try { - _validator = (AbstractValidator)_validatorConfigElement.createExecutableExtension(ExtensionConstants.AttribClass); - } - catch (Exception e){ - ValidationPlugin.getPlugin().handleException(e); - IContributor contrib = _validatorConfigElement.getContributor(); - String message = NLS.bind(ValMessages.ErrConfig, contrib.getName()); - ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, message); - _validator = new NullValidator(); - } - _validator.setParent(this); - _validatorConfigElement = null; - - } - return _validator; - } - - @Override - public String getValidatorClassname(){ - return _validatorClassName; - } - - public String[] getValidatorGroups(){ - return _validatorGroupIds; - } - - @Override - public int hashCodeForConfig() { - int h = super.hashCodeForConfig(); - if (_id != null)h += _id.hashCode(); - if (_groups != null){ - for (FilterGroup fg : _groups)h += fg.hashCodeForConfig(); - } - return h; - } - - @Override - public boolean isChanged() { - if (_changeCountGroups > 0)return true; - return super.isChanged(); - } - - @Override - boolean isLoaded() { - return _validator != null; - } - - @Override - public boolean shouldClearMarkers(ValidationEvent event) { - return getValidator().shouldClearMarkers(event); - } - - /** - * Answer true if this validator, based on it's filters, should validate this resource. - * - * @return true if the resource should be validated. - */ - @Override - protected boolean shouldValidate(IResource resource, ContentTypeWrapper contentTypeWrapper) { - if (resource.isDerived()){ - return false; - } - FilterGroup[] groups = getGroups(); - IProject project = resource.getProject(); - for (FilterGroup group : groups){ - if (!group.shouldValidate(project, resource, contentTypeWrapper))return false; - } - return true; - } - - - @Override - public void setDelegatingId(String delegating) { - super.setDelegatingId(delegating); - _delegated = null; - } - - public synchronized void setGroups(List<FilterGroup> groups){ - _groups = groups; - _groupsArray = null; - bumpChangeCountGroups(); - } - - public void setId(String id) { - if (!Misc.same(_id, id)){ - _id = id; - bumpChangeCountGlobal(); - } - } - - public void setName(String name) { - if (!Misc.same(_name, name)){ - _name = name; - bumpChangeCountGlobal(); - } - } - - @Override - public ValidationResult validate(IResource resource, int kind, ValOperation operation, IProgressMonitor monitor){ - return validate(resource, kind, operation, monitor, null); - } - - @Override - public ValidationResult validate(IResource resource, int kind, ValOperation operation, IProgressMonitor monitor, ValidationEvent event) { - ValidationResult vr = null; - if (operation == null)operation = new ValOperation(); - if (monitor == null)monitor = new NullProgressMonitor(); - try { - if (event == null)event = new ValidationEvent(resource, kind, null); - vr = getDelegatedValidator().validate(event, operation.getState(), monitor); - if (vr == null)vr = getDelegatedValidator().validate(resource, kind, operation.getState(), monitor); - } - catch (Exception e){ - try { - String msg = NLS.bind(ValMessages.LogValEnd, getName(), resource.getLocationURI()); - ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, msg); - } - catch (Exception e2 ){ - // ignore it - } - ValidationPlugin.getPlugin().handleException(e); - } - - if (vr != null){ - if (vr.getValidationException() != null){ - ValidationPlugin.getPlugin().handleException(vr.getValidationException()); - } - updateResults(vr); - if (vr.getDependsOn() != null){ - ValidationFramework.getDefault().getDependencyIndex().set(getId(), resource, vr.getDependsOn()); - } - IResource[] validated = vr.getValidated(); - if (validated != null){ - for (int i=0; i<validated.length; i++){ - operation.addValidated(getId(), validated[i]); - } - } - - ValidatorMessage[] msgs = vr.getMessages(); -// if (sanityTest(msgs.length, resource)){ - MarkerManager mm = MarkerManager.getDefault(); - for (ValidatorMessage m : msgs){ - mm.createMarker(m, getId()); - } -// } -// else { -// setBuildValidation(false); -// setManualValidation(false); -// } - } - return vr; - } - - /** - * Perform a simple sanity test to ensure that the validator is configured correctly. - * @param numberofMessages number of messages that the validator produced. - * @return true if the test passed - */ -// private boolean sanityTest(int numberofMessages, IResource resource) { -// if (numberofMessages < 201)return true; -// -// String resName = ""; //$NON-NLS-1$ -// if (resource != null)resName = resource.getName(); -// String message = NLS.bind(ValMessages.ConfigError, new Object[]{ -// getName(), getId(), String.valueOf(numberofMessages), resName}); -// ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, message); -// -// return false; -// } - - /** - * If the validator is using a report helper then update it with any of the messages that were - * added directly to the validation result. - * @param vr - */ - private void updateResults(ValidationResult vr) { - ReporterHelper rh = vr.getReporterHelper(); - if (rh == null)return; - ClassLoader classloader = getDelegatedValidator().getClass().getClassLoader(); - for (IMessage message : rh.getMessages()){ - Object target = message.getTargetObject(); - if (target != null){ - IResource res = null; - if (target instanceof IResource)res = (IResource)target; - if (res == null){ - target = message.getAttribute(IMessage.TargetResource); - if (target != null && target instanceof IResource)res = (IResource)target; - } - if (res != null){ - - ValidatorMessage vm = ValidatorMessage.create(message.getText(classloader), res); - if (getMarkerId() != null)vm.setType(getMarkerId()); - vr.add(vm); - int markerSeverity = IMarker.SEVERITY_INFO; - int sev = message.getSeverity(); - if ((sev & IMessage.HIGH_SEVERITY) != 0)markerSeverity = IMarker.SEVERITY_ERROR; - else if ((sev & IMessage.NORMAL_SEVERITY) != 0)markerSeverity = IMarker.SEVERITY_WARNING; - vm.setAttribute(IMarker.SEVERITY, markerSeverity); - vm.setAttribute(IMarker.LINE_NUMBER, message.getLineNumber()); - int offset = message.getOffset(); - if (offset != IMessage.OFFSET_UNSET){ - vm.setAttribute(IMarker.CHAR_START, offset); - int len = message.getLength(); - if (len != IMessage.OFFSET_UNSET){ - vm.setAttribute(IMarker.CHAR_START, offset); - vm.setAttribute(IMarker.CHAR_END, offset+len); - } - } - String groupName = message.getGroupName(); - if (groupName != null){ - vm.setAttribute(ConfigurationConstants.VALIDATION_MARKER_GROUP, groupName); - } - - copyAttributes(message, vm); - } - } - } - } - - @SuppressWarnings("unchecked") - private void copyAttributes(IMessage message, ValidatorMessage vm) { - // I made this a separate method, so that I could localize the suppression of unchecked warnings. - Map attributes = message.getAttributes(); - if (attributes != null){ - for (Iterator it = attributes.entrySet().iterator(); it.hasNext();){ - Map.Entry me = (Map.Entry)it.next(); - String key = (String)me.getKey(); - vm.setAttribute(key, me.getValue()); - } - } - } - - @Override - public void validationStarting(IProject project, ValidationState state, IProgressMonitor monitor) { - if (project == null)_pendingValidationStarted.set(true); - else { - AbstractValidator val = getDelegatedValidator(); - if (_pendingValidationStarted.getAndSet(false)){ - val.validationStarting(null, state, monitor); - } - val.validationStarting(project, state, monitor); - } - } - - @Override - public void validationFinishing(IProject project, ValidationState state, IProgressMonitor monitor) { - if (project == null){ - if (!_pendingValidationStarted.getAndSet(false))getDelegatedValidator().validationFinishing(null, state, monitor); - } - else getDelegatedValidator().validationFinishing(project, state, monitor); - } - - @SuppressWarnings("unchecked") - public Object getAdapter(Class adapter) { - return Platform.getAdapterManager().getAdapter(this, adapter); - } - - public synchronized void remove(FilterGroup group) { - _groups.remove(group); - _groupsArray = null; - bumpChangeCountGroups(); - } - - @Override - public void resetChangeCounters() { - super.resetChangeCounters(); - _changeCountGroups = 0; - } - - @Override - protected boolean shouldValidateProject(IProject project) { - FilterGroup[] groups = getGroups(); - ContentTypeWrapper ctw = new ContentTypeWrapper(); - for (FilterGroup group : groups){ - if (!group.shouldValidate(project, null, ctw))return false; - } - return true; - } - - public synchronized void replaceFilterGroup(FilterGroup existing, FilterGroup merged) { - remove(existing); - add(merged); - } - -} - -public String getSourceId() { - return _sourceId; -} - -public void setSourceId(String sourceId) { - if (!Misc.same(_sourceId, sourceId)){ - _sourceId = sourceId; - bumpChangeCountGlobal(); - } -} - - -void setMessages(Map<String, MessageSeveritySetting> map) { - _messageSettings = map; - bumpChangeCountMessages(); -} - -public int getChangeCountGlobal() { - return _changeCountGlobal; -} - -public boolean hasGlobalChanges(){ - return _migrated || _changeCountGlobal > 0; -} - -public int getChangeCountMessages() { - return _changeCountMessages; -} - -public void bumpChangeCountMessages(){ - _changeCountMessages++; -} - -public void resetChangeCounters() { - _changeCountGlobal = 0; - _changeCountMessages = 0; -} - -public void bumpChangeCountGlobal(){ - _changeCountGlobal++; -} - -/** - * Answer true if you have the same configuration settings as validator. - * @param validator this can be null. - */ -public boolean sameConfig(Validator validator) { - if (validator == null)return false; - return hashCodeForConfig() == validator.hashCodeForConfig(); -} - -public String getMarkerId() { - return _markerId; -} - -public void setMarkerId(String markerId) { - _markerId = markerId; - if (markerId != null)MarkerManager.getDefault().getMarkers().add(markerId); -} - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidatorMessage.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidatorMessage.java deleted file mode 100644 index a16c26ee2..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/ValidatorMessage.java +++ /dev/null @@ -1,296 +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.wst.validation; - - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.Assert; -import org.eclipse.wst.validation.internal.Tracing; -import org.eclipse.wst.validation.internal.ValConstants; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -/** - * This class provides a way for a validator to return messages, that are easily - * converted into IMarkers. - * <p> - * This class is completely optional for validators. A validator can choose to - * directly manage IMarkers. However, some validators want to be used in - * multiple contexts, for example as-you-type validation and build based - * validation. For these types of validators it is not possible for them to use - * only IMarkers, because often the Resource has not been saved yet. - * </p> - * <p> - * <b>Provisional API:</b> This class/interface is part of an interim API that - * is still under development and expected to change significantly before - * reaching stability. It is being made available at this early stage to solicit - * feedback from pioneering adopters on the understanding that any code that - * uses this API will almost certainly be broken (repeatedly) as the API - * evolves. - * </p> - */ -public class ValidatorMessage { - - public static final String ValidationId = "ValidationId"; //$NON-NLS-1$ - - /** Associate some arbitrary attributes with a message. */ - private final Map<String, Object> _map = new HashMap<String, Object>(5); - - private IResource _resource; - - /** The type of marker. */ - private String _type; - - /** - * Create a new validation message. - * - * @param message - * The localized message that will be displayed to the user. - * - * @param resource - * The resource that the message is associated with. - */ - public static ValidatorMessage create(String message, IResource resource){ - ValidatorMessage msg = new ValidatorMessage(); - msg._type = ValConstants.ProblemMarker; - msg._resource = resource; - msg.setAttribute(IMarker.MESSAGE, ValidationPlugin.getPlugin().isDebugging() ? - Tracing.timestampIt(message): message); - return msg; - } - - private ValidatorMessage(){} - - /** - * Answer a copy of yourself. - */ - public ValidatorMessage asCopy(){ - ValidatorMessage msg = new ValidatorMessage(); - msg._resource = _resource; - msg._type = _type; - msg._map.putAll(_map); - return msg; - } - - /** - * Returns the attribute with the given name. The result is an instance of - * one of the following classes: <code>String</code>, <code>Integer</code>, - * or <code>Boolean</code>. Returns <code>null</code> if the attribute is - * undefined. - * - * @param attributeName - * The name of the attribute. - * @return the value, or <code>null</code> if the attribute is undefined. - */ - public Object getAttribute(String attributeName){ - return _map.get(attributeName); - } - - /** - * Returns the integer valued attribute with the given name. Returns the - * given default value if the attribute is undefined or the marker does not - * exist or is not an integer value. - * - * @param attributeName - * The name of the attribute. - * @param defaultValue - * The value to use if no integer value is found. - * @return the value or the default value if no integer value was found. - */ - public int getAttribute(String attributeName, int defaultValue){ - Integer value = null; - try { - value = (Integer)_map.get(attributeName); - } - catch (Exception e){ - // eat it - } - if (value == null)return defaultValue; - return value.intValue(); - } - - /** - * Returns the string valued attribute with the given name. Returns the - * given default value if the attribute is undefined or the marker does not - * exist or is not a string value. - * - * @param attributeName - * The name of the attribute. - * @param defaultValue - * The value to use if no value is found. - * @return the value or the default value if no value was found. - */ - public String getAttribute(String attributeName, String defaultValue){ - String value = null; - try { - value = (String)_map.get(attributeName); - } - catch (Exception e){ - // eat it - } - if (value == null)return defaultValue; - return value; - - } - - /** - * Returns the boolean valued attribute with the given name. Returns the - * given default value if the attribute is undefined or the marker does not - * exist or is not a boolean value. - * - * @param attributeName - * The name of the attribute. - * @param defaultValue - * The value to use if no value is found. - * @return the value or the default value if no value was found. - */ - public boolean getAttribute(String attributeName, boolean defaultValue){ - Boolean value = null; - try { - value = (Boolean)_map.get(attributeName); - } - catch (Exception e){ - // eat it - } - if (value == null)return defaultValue; - return value.booleanValue(); - - } - - /** - * Returns a map with all the attributes for the marker. If the marker has - * no attributes then <code>null</code> is returned. - * - * @return a map of attribute keys and values (key type : - * <code>String</code> value type : <code>String</code>, - * <code>Integer</code>, or <code>Boolean</code>) or <code>null</code>. - */ - @SuppressWarnings("unchecked") - public Map getAttributes() { - return _map; - } - - /** - * Returns the resource with which this marker is associated. - * - * @return the resource with which this marker is associated - */ - public IResource getResource(){ - return _resource; - } - - /** - * Returns the type of this marker. The returned marker type will not be - * <code>null</code>. - * - * @return the type of this marker - */ - public String getType() { - return _type; - } - - /** - * Sets the marker type. - * - * @param type The marker id to use when creating new markers. - */ - public void setType(String type){ - assert type != null; - _type = type; - } - - /** - * Sets the integer valued attribute with the given name. - * <p> - * This method changes resources; these changes will be reported in a - * subsequent resource change event, including an indication that this - * marker has been modified. - * </p> - * - * @param attributeName - * The name of the attribute. - * @param value - * The value. - */ - public void setAttribute(String attributeName, int value){ - _map.put(attributeName, new Integer(value)); - - } - - /** - * Sets the attribute with the given name. The value must be - * <code>null</code> or an instance of one of the following classes: - * <code>String</code>, <code>Integer</code>, or <code>Boolean</code>. - * - * @param attributeName - * The name of the attribute. - * @param value - * The value, or <code>null</code> if the attribute is to be undefined. - */ - public void setAttribute(String attributeName, Object value){ - _map.put(attributeName, value); - } - - /** - * Sets the boolean valued attribute with the given name. - * - * @param attributeName - * The name of the attribute. - * @param value - * The value. - */ - public void setAttribute(String attributeName, boolean value){ - _map.put(attributeName, value ? Boolean.TRUE : Boolean.FALSE); - } - - /** - * Sets the given attribute key-value pairs on this marker. The values must - * be <code>null</code> or an instance of one of the following classes: - * <code>String</code>, <code>Integer</code>, or <code>Boolean</code>. If a - * value is <code>null</code>, the new value of the attribute is considered - * to be undefined. - * - * @param attributeNames - * An array of attribute names. - * @param values - * An array of attribute values. - */ - public void setAttributes(String[] attributeNames, Object[] values){ - Assert.isTrue(attributeNames.length == values.length); - for (int i=0; i<attributeNames.length; i++){ - setAttribute(attributeNames[i], values[i]); - } - } - - /** - * Sets the attributes for this marker to be the ones contained in the given - * table. The values must be an instance of one of the following classes: - * <code>String</code>, <code>Integer</code>, or <code>Boolean</code>. - * Attributes previously set on the marker but not included in the given map - * are considered to be removals. This includes the text of the message. - * Setting the given map to be - * <code>null</code> is equivalent to removing all marker attributes. - * - * @param attributes - * A map of attribute names to attribute values (key type : - * <code>String</code> value type : <code>String</code>, - * <code>Integer</code>, or <code>Boolean</code>) or <code>null</code>. - */ - public void setAttributes(Map<String, Object> attributes) { - _map.clear(); - _map.putAll(attributes); - - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/doc-files/faq.html b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/doc-files/faq.html deleted file mode 100644 index 8096d0a33..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/doc-files/faq.html +++ /dev/null @@ -1,40 +0,0 @@ -<html> -<head> -<title>Validation Framework - Frequently Asked Questions</title> -</head> -<body> -<h1>Validation Framework - Frequently Asked Questions</h1> -<h3>How do I create Problem Markers?</h3> -<p>There are three different ways to create problem markers.</p> -<ol> - <li>Use the native support in the validation framework.</li> - <li>Manage your own markers.</li> - <li>Use the support in the previous version of the validation framework.</li> -</ol> -<p>The first approach, is the recommended approach.</p> - -<h4>1. Use the native support in the validation framework</h4> -<p>After you have finished performing your validation, and are returning control back to -the validation framework, add your messages into the -<a href="../ValidationResult.html">ValidationResult</a> by using -the <a href="../ValidationResult.html#add(org.eclipse.wst.validation.ValidatorMessage)">add(ValidatorMessage message)</a> method. - -<h4>2. Manage your own markers</h4> - -<p>Create and remove your own markers. So that summary information can still be displayed, set the counts of any newly -created markers in the <a href="../ValidationResult.html">ValidationResult</a> by using the setSeverityXXX() methods. -For example, if this validation pass generated two error markers, you would call -<a href="../ValidationResult.html#setSeverityError(int)">setSeverityError(2)</a>. -</p> - -<h4>3. Use the support in the previous version of the validation framework</h4> - -<p>If you are porting a validator that used the previous version of the validation framework, and you wish to continue to use an -<A HREF="../../../../../org/eclipse/wst/validation/internal/provisional/core/IReporter.html">IReporter</a> to -report your markers, you can continue to do so.</p> -<p>For this approach, use the -<a href="../ValidationResult.html#getReporter(IProgressMonitor)">getReporter(IProgressMonitor monitor)</a> method, -and return your messages through the IReporter. If this method is called it is assumed by the framework, -that this IReporter will be used as the only way of passing messages back to the framework. -</body> -</html>
\ No newline at end of file diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ContentTypeWrapper.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ContentTypeWrapper.java deleted file mode 100644 index 53dd045c1..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ContentTypeWrapper.java +++ /dev/null @@ -1,53 +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.wst.validation.internal; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -/** - * Since it can be expense to determine a content type, we provide a wrapper so that we only - * need to get it once, as we validate a resource. - * @author karasiuk - * - */ -public class ContentTypeWrapper { - - private IContentType _type; - private boolean _initialized; - - public IContentType getContentType(IFile file){ - if (_initialized)return _type; - - IContentDescription cd = null; - try { - cd = file.getContentDescription(); - } - catch (CoreException e){ - try { - file.refreshLocal(IResource.DEPTH_ZERO, null); - cd = file.getContentDescription(); - } - catch (CoreException e2){ - if (Tracing.isLogging())ValidationPlugin.getPlugin().handleException(e2); - } - } - if (cd == null)return null; - _type = cd.getContentType(); - _initialized = true; - return _type; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DebugConstants.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DebugConstants.java deleted file mode 100644 index a4662419e..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DebugConstants.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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.wst.validation.internal; - -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -public interface DebugConstants { - - /** matches - trace filter matches. */ - String TraceMatches = ValidationPlugin.PLUGIN_ID+"/matches"; //$NON-NLS-1$ - - /** timings - trace the times of the validators. */ - String TraceTimes = ValidationPlugin.PLUGIN_ID+"/timings"; //$NON-NLS-1$ - - /** v1 - trace the v1 validators. */ - String TraceV1 = ValidationPlugin.PLUGIN_ID+"/v1"; //$NON-NLS-1$ - - /** timings/tracefile - file that stores the trace events */ - String TraceTimesFile = ValidationPlugin.PLUGIN_ID+"/timings/tracefile"; //$NON-NLS-1$ - - /** - * timings/useDoubles - By default times that are written to the trace file are - * in milliseconds for elapsed time and nanoseconds for cpu time. - * If you find these times easier to read as seconds as expressed by a double, - * the following flag can be turned on. - */ - String TraceTimesUseDoubles = ValidationPlugin.PLUGIN_ID+"/timings/useDoubles"; //$NON-NLS-1$ - - /** - * extraValDetail - If extra detail is needed for a particular validator it's id can be specified here. - * For example, if you wanted more detail on the XML validator you would use org.eclipse.wst.xml.core.xml - */ - String ExtraValDetail = ValidationPlugin.PLUGIN_ID+"/extraValDetail"; //$NON-NLS-1$ - - /** - * filter/allExcept - If supplied, it is as if this is the only validator that gets defined via - * the extension point. All the other validators are ignored. - */ - String FilterAllExcept = ValidationPlugin.PLUGIN_ID+"/filter/allExcept"; //$NON-NLS-1$ - - /** - * trace/level - The tracing level. If not supplied a default of zero is used. The higher the number the - * more verbose the tracing. - */ - String TraceLevel = ValidationPlugin.PLUGIN_ID+"/trace/level"; //$NON-NLS-1$ - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DependencyIndex.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DependencyIndex.java deleted file mode 100644 index 40c0b6400..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DependencyIndex.java +++ /dev/null @@ -1,369 +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.wst.validation.internal; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.ISaveContext; -import org.eclipse.core.resources.ISaveParticipant; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.validation.DependentResource; -import org.eclipse.wst.validation.IDependencyIndex; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -/** - * A simple implementation of the IDependencyIndex. This will probably be - * replaced with a higher performance, more robust index, at some point in the - * future. - * <p> - * The format of the index is: - * - * <pre> - * Version number - * Number of depends on entries - * depends on file name - * number of dependent entries - * dependent file name - * number of validators - * validator id - * </pre> - * - * @author karasiuk - */ -public class DependencyIndex implements IDependencyIndex, ISaveParticipant { - - /** - * An index so that we can determine which things depend on this resource. - */ - private Map<IResource,Set<Depends>> _dependsOn; - - /** - * An index so that we can determine who the resource depends on. - */ - private Map<IResource,Set<Depends>> _dependents; - private boolean _dirty; - - private static IResource[] EmptyResources = new IResource[0]; - - /** Version of the persistent index. */ - private static final int CurrentVersion = 1; - - public synchronized void add(String id, IResource dependent, IResource dependsOn) { - init(); - if (dependsOn == null || dependent == null)return; - Depends d = getOrCreateDepends(dependent, dependsOn); - if (d.getValidators().add(id))_dirty = true; - } - - private Depends getOrCreateDepends(IResource dependent, IResource dependsOn) { - Set<Depends> set = getSet(_dependents, dependent); - for (Depends d : set){ - if (d.getDependsOn() != null && d.getDependsOn().equals(dependsOn)) return d; - } - Depends d = new Depends(dependent, dependsOn); - _dirty = true; - set.add(d); - - getSet(_dependsOn, dependsOn).add(d); - return d; - } - - /** - * Answer the set for the resource, creating it if you need to. - */ - private Set<Depends> getSet(Map<IResource, Set<Depends>> map, IResource resource) { - Set<Depends> set = map.get(resource); - if (set == null){ - set = new HashSet<Depends>(5); - map.put(resource, set); - } - return set; - } - - /** - * Restore the dependency index. See the class comment for the structure. - */ - private void init() { - if (_dependsOn != null)return; - - boolean error = false; - File f = getIndexLocation(); - if (!f.exists()){ - _dependsOn = new HashMap<IResource,Set<Depends>>(100); - _dependents = new HashMap<IResource,Set<Depends>>(100); - } - else { - String errorMessage = ValMessages.Error21; - DataInputStream in = null; - try { - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - in = new DataInputStream(new FileInputStream(f)); - - int version = in.readInt(); - if (version != CurrentVersion){ - error = true; - String msg = NLS.bind(ValMessages.ErrDependencyVersion, CurrentVersion); - throw new IllegalStateException(msg); - } - int numDependsOn = in.readInt(); - _dependsOn = new HashMap<IResource,Set<Depends>>(numDependsOn+100); - _dependents = new HashMap<IResource,Set<Depends>>(numDependsOn+100); - for (int i=0; i<numDependsOn; i++){ - String v = in.readUTF(); - IResource dependsOn = root.findMember(v); - if (dependsOn == null){ - Tracing.log(NLS.bind(errorMessage, v)); - } - int numDependents = in.readInt(); - for (int j=0; j<numDependents; j++){ - v = in.readUTF(); - IResource dependent = root.findMember(v); - if (dependent == null){ - Tracing.log(NLS.bind(errorMessage, v)); - } - int numVal = in.readInt(); - for (int k=0; k<numVal; k++){ - String id = in.readUTF(); - if (dependent != null && dependsOn != null)add(id, dependent, dependsOn); - } - } - } - } - catch (IOException e){ - error = true; - ValidationPlugin.getPlugin().handleException(e); - } - finally { - Misc.close(in); - if (error){ - _dependsOn = new HashMap<IResource,Set<Depends>>(100); - _dependents = new HashMap<IResource,Set<Depends>>(100); - f.delete(); - } - } - } - } - - public synchronized void clear(IProject project) { - init(); - for (Map.Entry<IResource,Set<Depends>> me : _dependents.entrySet()){ - if (me.getKey().getProject() == project){ - for (Depends d : me.getValue()){ - if (d.delete())_dirty = true; - } - } - } - } - - public synchronized IResource[] get(String validatorId, IResource dependsOn) { - init(); - List<IResource> list = new LinkedList<IResource>(); - Set<Depends> set = getSet(_dependsOn, dependsOn); - for (Depends d : set){ - for (String id : d.getValidators()){ - if (validatorId.equals(id))list.add(d.getDependent()); - } - } - - if (list.size() == 0)return EmptyResources; - IResource[] resources = new IResource[list.size()]; - list.toArray(resources); - return resources; - } - - - public synchronized List<DependentResource> get(IResource dependsOn) { - init(); - List<DependentResource> list = new LinkedList<DependentResource>(); - Set<Depends> set = getSet(_dependsOn, dependsOn); - ValManager vm = ValManager.getDefault(); - for (Depends d : set){ - for (String id : d.getValidators()){ - Validator v = vm.getValidator(id, d.getDependent().getProject()); - if (v != null)list.add(new DependentResource(d.getDependent(), v)); - } - } - return list; - } - - - public synchronized void set(String id, IResource dependent, IResource[] dependsOn) { - init(); - Set<Depends> set = getSet(_dependents, dependent); - for (Depends d : set){ - if (d.delete(id))_dirty = true; - } - if (dependsOn != null){ - for (IResource d : dependsOn)add(id, dependent, d); - } - } - - public boolean isDependedOn(IResource resource) { - init(); - Set<Depends> set = _dependsOn.get(resource); - if (set == null || set.size() == 0)return false; - return true; - } - - public void doneSaving(ISaveContext context) { - } - - public void prepareToSave(ISaveContext context) throws CoreException { - } - - public void rollback(ISaveContext context) { - } - - /** - * Persist the dependency index. See the class comment for the structure. - */ - public synchronized void saving(ISaveContext context) throws CoreException { - if (!_dirty)return; - _dirty = false; - - DataOutputStream out = null; - try { - File f = getIndexLocation(); - out = new DataOutputStream(new FileOutputStream(f)); - out.writeInt(CurrentVersion); - Map<String, Set<DependsResolved>> map = compress(_dependsOn); - out.writeInt(map.size()); - for (Map.Entry<String, Set<DependsResolved>> me : map.entrySet()){ - out.writeUTF(me.getKey()); - Set<DependsResolved> set = me.getValue(); - out.writeInt(set.size()); - for (DependsResolved d : set){ - out.writeUTF(d.resource); - out.writeInt(d.validators.size()); - for (String id : d.validators){ - out.writeUTF(id); - } - } - } - } - catch (IOException e){ - ValidationPlugin.getPlugin().handleException(e); - } - finally { - Misc.close(out); - } - } - - private Map<String, Set<DependsResolved>> compress(Map<IResource, Set<Depends>> dependsOn) { - Map<String, Set<DependsResolved>> map = new HashMap<String, Set<DependsResolved>>(dependsOn.size()); - for (Map.Entry<IResource, Set<Depends>> me : dependsOn.entrySet()){ - Set<DependsResolved> set = new HashSet<DependsResolved>(me.getValue().size()); - for (Depends d : me.getValue()){ - IPath path = d.getDependent().getFullPath(); - if (path != null){ - DependsResolved dr = new DependsResolved(); - dr.resource = path.toPortableString(); - if (d.getValidators().size() > 0){ - dr.validators = d.getValidators(); - set.add(dr); - } - } - } - if (set.size() > 0){ - IResource res = me.getKey(); - if (res != null){ - IPath path = res.getFullPath(); - if (path != null)map.put(path.toPortableString(), set); - } - } - } - return map; - } - - private File getIndexLocation() { - IPath path = ValidationPlugin.getPlugin().getStateLocation().append("dep.index"); //$NON-NLS-1$ - return path.toFile(); - } - - /** - * Keep track of a relationship between a dependent and the thing that it - * depends on. - * - * @author karasiuk - * - */ - private static class Depends { - - /** The resource that is being depended on, for example a.xsd */ - private IResource _dependsOn; - - /** The resource that is dependent, for example a.xml */ - private IResource _dependent; - - /** The id's of the validators that have asserted the dependency. */ - private Set<String> _validators; - - public Depends(IResource dependent, IResource dependsOn) { - _dependent = dependent; - _dependsOn = dependsOn; - _validators = new HashSet<String>(5); - } - - /** - * Answer true if the id was deleted. - */ - public boolean delete(String id) { - return _validators.remove(id); - } - - /** - * Delete all the dependency assertions for all of your validators. - * @return false if there was nothing to delete - */ - public boolean delete() { - boolean deleted = _validators.size() > 0; - if (deleted)_validators.clear(); - return deleted; - } - - public IResource getDependsOn() { - return _dependsOn; - } - - public IResource getDependent() { - return _dependent; - } - - public Set<String> getValidators() { - return _validators; - } -} - - private static class DependsResolved { - String resource; - Set<String> validators; - } - - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Deserializer.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Deserializer.java deleted file mode 100644 index b1af963e6..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Deserializer.java +++ /dev/null @@ -1,63 +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.wst.validation.internal; - -/** - * A simple deserializer that knows how to retrieve booleans, integers and strings, from a string - * that was encoded by the Serializer class. - * - * @see Serializer - * @author karasiuk - * - */ -public class Deserializer { - private char[] _buffer; - private int _posn; - - public Deserializer(String value){ - _buffer = value.toCharArray(); - } - - public boolean getBoolean(){ - boolean result = false; - if (_buffer[_posn] == 'T')result = true; - else if (_buffer[_posn] == 'F')result = false; - else throw new IllegalStateException(ValMessages.DecodeError1); - - _posn++; - return result; - } - - public String getString(){ - int len = getInt(); - String result = new String(_buffer, _posn, len); - _posn += len; - return result; - } - - public int getInt(){ - Integer len = new Integer(String.valueOf(_buffer[_posn])); - _posn++; - - String s = String.valueOf(_buffer, _posn, len+1); - _posn += len+1; - return Integer.parseInt(s); - } - - /** - * Are there any more items? - * @return - */ - public boolean hasNext() { - if (_posn >= _buffer.length)return false; - return true; - } -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledResourceManager.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledResourceManager.java deleted file mode 100644 index 120180fff..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledResourceManager.java +++ /dev/null @@ -1,158 +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.wst.validation.internal; - -import java.util.HashSet; -import java.util.Set; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; -import org.osgi.service.prefs.BackingStoreException; - -/** - * Validators can assert that certain resources (usually folders) are not validated. This class keeps track of those - * assertions. - * @author karasiuk - * - */ -public class DisabledResourceManager implements IProjectChangeListener { - - public static DisabledResourceManager getDefault(){ - return Singleton.disabledResourceManager; - } - - private Set<IResource> _disabled = new HashSet<IResource>(100); - private Set<IProject> _loadedProjects = new HashSet<IProject>(40); - - private DisabledResourceManager(){ - EventManager.getManager().addProjectChangeListener(this); - } - - public void disableValidation(IResource resource){ - // We check for two reasons, 1) we may save some work, 2) we force the project to be loaded - if (isDisabled(resource))return; - - Set<IResource> copy = new HashSet<IResource>(_disabled.size()+2); - copy.addAll(_disabled); - copy.add(resource); - save(copy, resource.getProject()); - _disabled = copy; - } - - public void enableValidation(IResource resource){ - // We check for two reasons, 1) we may save some work, 2) we force the project to be loaded - if (!isDisabled(resource))return; - - Set<IResource> copy = new HashSet<IResource>(_disabled.size()+2); - copy.addAll(_disabled); - copy.remove(resource); - save(copy, resource.getProject()); - _disabled = copy; - } - - private void save(Set<IResource> disabled, IProject project) { - Serializer ser = new Serializer(200); - for (IResource resource : disabled){ - if (project == resource.getProject()){ - ser.put(resource.getProjectRelativePath().toPortableString()); - } - } - PreferencesWrapper prefs = PreferencesWrapper.getPreferences(project, null); - prefs.put(PrefConstants.disabled, ser.toString()); - try { - prefs.flush(); - } - catch (BackingStoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - - private void load(IProject project){ - Set<IResource> copy = new HashSet<IResource>(_disabled.size()+10); - copy.addAll(_disabled); - PreferencesWrapper prefs = PreferencesWrapper.getPreferences(project, null); - String disabled = prefs.get(PrefConstants.disabled, ""); //$NON-NLS-1$ - if (disabled.length() > 0){ - Deserializer des = new Deserializer(disabled); - while(des.hasNext()){ - String pathString = des.getString(); - IPath path = Path.fromPortableString(pathString); - IResource resource = project.findMember(path); - copy.add(resource); - } - } - _disabled = copy; - } - - public void dispose(){ - EventManager.getManager().removeProjectChangeListener(this); - } - - /** - * Answer true if this resource should not be validated. - * - * @param resource the resource that is being tested. - * @return true if the resource should not be validated. - */ - public boolean isDisabled(IResource resource){ - IProject project = resource.getProject(); - if (_loadedProjects.contains(project))return _disabled.contains(resource); - return isDisabled(resource, project); - } - - private synchronized boolean isDisabled(IResource resource, IProject project){ - if (!_loadedProjects.contains(project)){ - load(project); - _loadedProjects.add(project); - } - return _disabled.contains(resource); - } - - public void addDisabled(IResource resource){ - _disabled.add(resource); - } - - public void projectChanged(IProject project, int type) { - switch (type) { - case IProjectChangeListener.ProjectDeleted: - case IProjectChangeListener.ProjectClosed: - projectRemoved(project); - break; - - } - - } - - private synchronized void projectRemoved(IProject project) { - _loadedProjects.remove(project); - Set<IResource> copy = new HashSet<IResource>(100); - for (IResource resource : _disabled){ - if (resource.getProject() != project)copy.add(resource); - } - _disabled = copy; - } - - /** - * Store the singleton for the DisabledResourceManager. This approach is used to avoid having to synchronize the - * DisabledResourceManager.getDefault() method. - * - * @author karasiuk - * - */ - private static class Singleton { - static DisabledResourceManager disabledResourceManager = new DisabledResourceManager(); - } - - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledValidatorManager.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledValidatorManager.java deleted file mode 100644 index 8a141c5c8..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/DisabledValidatorManager.java +++ /dev/null @@ -1,135 +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.wst.validation.internal; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.internal.model.IValidatorVisitor; - -/** - * Keep track of the disabled validators. - * @author karasiuk - * - */ -public final class DisabledValidatorManager implements IValChangedListener { - - private static final AtomicInteger _counter = new AtomicInteger(); - private static final int CacheSize = 5; - - private final Map<IResource, LRUSet> _map = Collections.synchronizedMap(new HashMap<IResource, LRUSet>(5)); - - public static DisabledValidatorManager getDefault(){ - return Singleton.disabledValidatorManager; - } - - private DisabledValidatorManager(){ - ValPrefManagerProject.addListener(this); - } - - /* - * Although this is currently not called, it should be if this ever stops being a singleton. - */ - public void dispose(){ - ValPrefManagerProject.removeListener(this); - } - - public Set<Validator> getDisabledValidatorsFor(IResource resource) { - LRUSet set = _map.get(resource); - if (set != null){ - set.counter = _counter.getAndIncrement(); - return set.validators; - } - - DisabledValidationFinder dvf = new DisabledValidationFinder(); - Set<Validator> vset = dvf.findDisabledValidatorsFor(resource); - insert(resource, vset); - return vset; - } - - private synchronized void insert(IResource resource, Set<Validator> vset) { - if (_map.size() >= CacheSize ){ - IResource oldest = null; - int current = Integer.MAX_VALUE; - for (Map.Entry<IResource, LRUSet> me : _map.entrySet()){ - if (me.getValue().counter < current){ - oldest = me.getKey(); - current = me.getValue().counter; - } - } - _map.remove(oldest); - } - LRUSet set = new LRUSet(); - set.counter = _counter.getAndIncrement(); - set.validators = vset; - _map.put(resource, set); - } - - - private final static class LRUSet { - int counter; - Set<Validator> validators; - } - - private final static class DisabledValidationFinder implements IValidatorVisitor { - - private Map<String, Validator> _validators; - - public void visit(Validator validator, IProject project, ValType valType, ValOperation operation, - IProgressMonitor monitor) { - - _validators.remove(validator.getId()); - - } - - public Set<Validator> findDisabledValidatorsFor(IResource resource) { - ValManager vm = ValManager.getDefault(); - Validator[] vals = vm.getValidatorsCopy(); - _validators = new HashMap<String, Validator>(100); - for (Validator v : vals)_validators.put(v.getId(), v); - - IProject project = resource.getProject(); - vm.accept(this, project, resource, ValType.Build, new ValOperation(), new NullProgressMonitor()); - Set<Validator> set = new HashSet<Validator>(_validators.size()); - set.addAll(_validators.values()); - return set; - } - - - } - - public void validatorsForProjectChanged(IProject project, boolean configSettingChanged) { - _map.clear(); - } - - - /** - * Store the singleton for the DisabledValidatorManager. This approach is used to avoid having to synchronize the - * DisabledValidatorManager.getDefault() method. - * - * @author karasiuk - * - */ - private final static class Singleton { - final static DisabledValidatorManager disabledValidatorManager = new DisabledValidatorManager(); - } - - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionConstants.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionConstants.java deleted file mode 100644 index e70247144..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionConstants.java +++ /dev/null @@ -1,183 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 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.wst.validation.internal; - -/** - * Constants used in the extension points. - * @author karasiuk - * - */ -public interface ExtensionConstants { - - /** validatorV2 - extension point for registering validators that use version 2 of the validation framework. */ - String validator = "validatorV2"; //$NON-NLS-1$ - - /** exclude - extension point for adding extra exclusion filters to a validator. */ - String excludeExtension = "exclude"; //$NON-NLS-1$ - - /** build - is the validator enabled by default for build based validations? true or false */ - String build = "build"; //$NON-NLS-1$ - - /** class - name of the attribute that holds the validator class. */ - String AttribClass = "class"; //$NON-NLS-1$ - - /** manual - is the validator enabled by default for manual based validations? true or false */ - String manual = "manual"; //$NON-NLS-1$ - - /** - * markerId - the marker id that the framework should use when creating customized markers for this validator. - * This is an optional attribute. If it is not supplied than the standard validation marker type will be used. - */ - String markerId = "markerId"; //$NON-NLS-1$ - - /** - * sourceid - If this validator also serves as an as-you-type validator (also know as an ISourceValidator) - * then it's source id is specified here, so that the two validators can be associated with one - * another. By source id, we mean the id that is used in the org.eclipse.wst.sse.ui.sourceValidation - * extension point. - */ - String sourceId = "sourceid"; //$NON-NLS-1$ - - /** - * version - the version of this definition. The attribute is a simple integer, and if not specified it - * is assumed to be 1. This allows the filter settings to be changed in the future. - */ - String version = "version"; //$NON-NLS-1$ - - /** - * include - a group of inclusion rules. At least one rule in this group needs to match in order for the resource - * to to considered to be validated. - */ - String include = "include"; //$NON-NLS-1$ - - /** exclude - a group of exclusion rules. If any of these rules match the resource is not validated. */ - String exclude = "exclude"; //$NON-NLS-1$ - - /** rules - a group of inclusion or exclusion rules. */ - String rules = "rules"; //$NON-NLS-1$ - - /** rules - extension point to declare a validator group */ - String group = "validatorGroup"; //$NON-NLS-1$ - - interface Group { - /* - * The group sub-element for either the validatorGroup or validator - * extension points. - */ - String elementGroup = "group"; //$NON-NLS-1$ - // a validator group identifier - String attId = "id"; //$NON-NLS-1$ - // the listener sub-element - String elementListener = "listener"; //$NON-NLS-1$ - // the group listener class name - String attClass = "class"; //$NON-NLS-1$ - } - - /** Different types of rules for filtering validation. */ - interface Rule { - - /** projectNature - filter by project nature. */ - String projectNature = "projectNature"; //$NON-NLS-1$ - - /** fileext - filter by file extension. */ - String fileext = "fileext"; //$NON-NLS-1$ - - /** file - a file name, it can include path information as well. */ - String file = "file"; //$NON-NLS-1$ - - /** facet - filter by facet id. */ - String facet = "facet"; //$NON-NLS-1$ - - /** contentType - filter by content type. */ - String contentType = "contentType"; //$NON-NLS-1$ - - /** pattern - filter paths by regular expression. */ - String pattern = "pattern"; //$NON-NLS-1$ - } - - /** Rule attributes */ - interface RuleAttrib { - - /** caseSensitive - true or false. */ - String caseSensitive = "caseSensitive"; //$NON-NLS-1$ - - /** - * exactMatch - true or false, default is true. It is used to decide whether content types need to match - * exactly, or whether sub types should also be considered. - */ - String exactMatch = "exactMatch"; //$NON-NLS-1$ - - /** ext - a file extension, for example "html". */ - String ext = "ext"; //$NON-NLS-1$ - - /** id - an identifier. */ - String id = "id"; //$NON-NLS-1$ - - /** name - a file name. */ - String name = "name"; //$NON-NLS-1$ - - /** regex - a Java regular expression. */ - String regex = "regex"; //$NON-NLS-1$ - - /** - * type - the type of file to be matched: - * <ul> - * <li>folder - project relative folder name - * <li>file - simple file name - * <li>full - fully qualified, project relative file name - * </ul> - */ - String fileType = "type"; //$NON-NLS-1$ - - /** version - facet version expression. See the facet framework for the exact syntax of this expression. */ - String version = "version"; //$NON-NLS-1$ - } - - interface FileType { - /** folder - project relative folder name */ - String folder = "folder"; //$NON-NLS-1$ - - /** file - simple file name */ - String file = "file"; //$NON-NLS-1$ - - /** full - fully qualified, project relative file name */ - String full = "full"; //$NON-NLS-1$ - } - - interface MessageCategory { - /** messageCategory - name of the message category element. */ - String name = "messageCategory"; //$NON-NLS-1$ - - /** id - simple id of the message. */ - String id = "id"; //$NON-NLS-1$ - - /** label = human readable label of the message category. */ - String label = "label"; //$NON-NLS-1$ - - /** severity - message severity, it must be one of error, warning or ignore. */ - String severity = "severity"; //$NON-NLS-1$ - - String sevError = "error"; //$NON-NLS-1$ - String sevWarning = "warning"; //$NON-NLS-1$ - String sevIgnore = "ignore"; //$NON-NLS-1$ - } - - interface Exclude { - /** id - fully qualified id of the validator that is being extended. */ - String id = "id"; //$NON-NLS-1$ - } - - /** true */ - String True = "true"; //$NON-NLS-1$ - - /** false */ - String False = "false"; //$NON-NLS-1$ -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionValidators.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionValidators.java deleted file mode 100644 index 090f4af06..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ExtensionValidators.java +++ /dev/null @@ -1,110 +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.wst.validation.internal; - -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.resources.IProject; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -/** - * The validators that have been defined by the validator extension points. - * @author karasiuk - * - */ -public final class ExtensionValidators { - private static ExtensionValidators _me; - - /** All the registered validators. The key is the validator id and the value is the validator. */ - private final Map<String, Validator> _map; - - public synchronized static ExtensionValidators instance(){ - if (_me == null){ - _me = new ExtensionValidators(); - } - return _me; - } - - private ExtensionValidators(){ - _map = new HashMap<String, Validator>(100); - for (Validator v : ValidatorExtensionReader.getDefault().process()){ - _map.put(v.getId(), v); - } - } - - /** - * Answer all the v2 validators that have been defined by the extension point. This is the real - * map (not a copy). - * - * @return The key is the validator id and the value is the validator. - */ - public Map<String, Validator> getMapV2() { - return _map; - } - - /** - * Answer all the v2 validators that have been defined by the extension point. This is a copy of - * the map, but not a copy of the validators. - * - * @return The key is the validator id and the value is the validator. - */ - public Map<String, Validator> getMapV2Copy() { - HashMap<String, Validator> map = new HashMap<String, Validator>(_map.size()); - map.putAll(_map); - return map; - } - - - /** - * Answer all the validators that have been defined by extension points. This includes all - * the v2 validators, and all of the v1 validators that have been defined just on this project. - * - * @return The key is the validator id and the value is the validator. - */ - public Map<String, Validator> getMap(IProject project) { - //TODO I may want to consider caching this, but then again if the v1 validators are going away - // it may not be worth it. - Map<String, Validator> map = new HashMap<String, Validator>(); - map.putAll(_map); - - for (Validator v : getV1Validators(project))map.put(v.getId(), v); - - return map; - } - - /** - * Answer the v1 validators that have been defined just on this project. - * @param project - * @return - */ - List<Validator> getV1Validators(IProject project){ - List<Validator> list = new LinkedList<Validator>(); - try { - ProjectConfiguration pc = new ProjectConfiguration(project); - pc.resetToDefault(); - for (ValidatorMetaData vmd : pc.getValidators()){ - Validator v = Validator.create(vmd, pc, project); - list.add(v); - } - } - catch (InvocationTargetException e){ - ValidationPlugin.getPlugin().handleException(e); - } - - return list; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/FullBuildJob.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/FullBuildJob.java deleted file mode 100644 index 332a2c790..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/FullBuildJob.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.eclipse.wst.validation.internal; - -import org.eclipse.core.resources.IncrementalProjectBuilder; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.resources.WorkspaceJob; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -public class FullBuildJob extends WorkspaceJob { - - public FullBuildJob(){ - super(ValMessages.JobName); - } - - @Override - public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { - try { - ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor); - } - catch (Exception e){ - return new Status(IStatus.ERROR,ValidationPlugin.PLUGIN_ID, e.toString(), e); - } - return Status.OK_STATUS; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IProjectChangeListener.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IProjectChangeListener.java deleted file mode 100644 index 678853499..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IProjectChangeListener.java +++ /dev/null @@ -1,39 +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.wst.validation.internal; - -import org.eclipse.core.resources.IProject; - -/** - * A call back for listeners that are interested when a project changes. - * @author karasiuk - * - */ -public interface IProjectChangeListener { - - int ProjectOpened = 1; - int ProjectClosed = 2; - int ProjectDeleted = 4; - - /** 8 - Something in the project description has changed. For example, a Nature was added. */ - int ProjectChanged = 8; - - /** 16 - The project has been added. */ - int ProjectAdded = 16; - - /** - * The project has changed in some way. - * - * @param project The project that has changed. - * @param type The type of change. This will be one of the Project constants; - */ - void projectChanged(IProject project, int type); -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IValChangedListener.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IValChangedListener.java deleted file mode 100644 index a2d26d80f..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/IValChangedListener.java +++ /dev/null @@ -1,31 +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.wst.validation.internal; - -/** - * A class that wants to be notified when the validator preferences change. - * @author karasiuk - * - */ -public interface IValChangedListener { - - /** - * The validators for the project have changed. - * - * @param project the project can be null, which means that the global validation preferences have - * changed. - * - * @param configSettingChanged If true a setting that could effect what gets validated has changed. - * If false, then only other types of settings (like whether to show a results dialog or not) have - * changed. - */ - public void validatorsForProjectChanged(org.eclipse.core.resources.IProject project, boolean configSettingChanged); -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/MarkerManager.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/MarkerManager.java deleted file mode 100644 index 8776525c7..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/MarkerManager.java +++ /dev/null @@ -1,205 +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.wst.validation.internal; - -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.ValidatorMessage; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; - -/** - * A central place to manage all of the V2 validation markers. - * @author karasiuk - * - */ -public class MarkerManager { - - private Set<String> _markers = new HashSet<String>(50); - - public static MarkerManager getDefault(){ - return Singleton.markerManager; - } - - private MarkerManager(){ - _markers.add(ValConstants.ProblemMarker); - _markers.add(ConfigurationConstants.VALIDATION_MARKER); - } - - /** - * Clear any validation markers that may have been set by this validator. - * - * @param resource - * The resource that may have it's markers cleared. It can be - * null, in which case the operation is a no-op. - * @param validator - * The validator that created the marker. - */ - public void clearMarker(IResource resource, Validator validator) throws CoreException { - if (resource == null)return; - hook(resource); - - String id = validator.getMarkerId(); - if (id != null){ - try { - resource.deleteMarkers(id, true, IResource.DEPTH_ZERO); - } - catch (CoreException e){ - // Nothing that we can do. This is not worth logging. - } - return; - } - - IMarker[] markers = resource.findMarkers(ValConstants.ProblemMarker, true, IResource.DEPTH_ZERO); - String valId = validator.getId(); - for (IMarker marker : markers){ - id = marker.getAttribute(ValidatorMessage.ValidationId, null); - if (valId.equals(id))marker.delete(); - } - } - - @SuppressWarnings("unchecked") - public void createMarker(ValidatorMessage m, String id){ - try { - IResource resource = m.getResource(); - hook(resource); - IMarker marker = resource.createMarker(m.getType()); - Map map = m.getAttributes(); - if (map.get(ValidatorMessage.ValidationId) == null) - map.put(ValidatorMessage.ValidationId, id); - marker.setAttributes(map); - } - catch (CoreException e){ - if (!m.getResource().exists())throw new ResourceUnavailableError(m.getResource()); - ValidationPlugin.getPlugin().handleException(e); - } - - } - - /** - * Delete all the markers on this resource that were created before the - * operation start time. - * - * @param resource - * The resource that is having it's markers deleted. - * @param operationStartTime - * The time as returned by System.currentTimeMillis(). - * @param depth - * The depth of the markers to clear. It is one of the - * IResource.DEPTH_XXX constants. - */ - public void deleteMarkers(IResource resource, long operationStartTime, int depth){ - try { - hook(resource); - IMarker[] markers = resource.findMarkers(null, true, depth); - String markerType; - for (IMarker marker : markers){ - try { - markerType = marker.getType(); - } - catch (CoreException e) - { - //ignore the marker - return; - } - if (_markers.contains(markerType)){ - long createTime = marker.getCreationTime(); - if (createTime < operationStartTime){ - try { - marker.delete(); - } - catch (CoreException e){ - // eat it - there is nothing we can do about this. - } - } - } - } - } - catch (CoreException e){ - IProject project = resource.getProject(); - if (!project.exists() || !project.isOpen())throw new ProjectUnavailableError(project); - if (!resource.exists())throw new ResourceUnavailableError(resource); - ValidationPlugin.getPlugin().handleException(e); - } - } - - public void makeMarkers(List<IMessage> list){ - for (IMessage message : list){ - IResource res = null; - Object target = message.getTargetObject(); - if (target != null && target instanceof IResource)res = (IResource)target; - if (res == null){ - target = message.getAttribute(IMessage.TargetResource); - if (target != null && target instanceof IResource)res = (IResource)target; - } - if (res != null){ - try { - hook(res); - String id = message.getMarkerId(); - if (id == null)id = ConfigurationConstants.VALIDATION_MARKER; - IMarker marker = res.createMarker(id); - marker.setAttributes(message.getAttributes()); - marker.setAttribute(IMarker.MESSAGE, message.getText()); - int markerSeverity = IMarker.SEVERITY_INFO; - int sev = message.getSeverity(); - if ((sev & IMessage.HIGH_SEVERITY) != 0)markerSeverity = IMarker.SEVERITY_ERROR; - else if ((sev & IMessage.NORMAL_SEVERITY) != 0)markerSeverity = IMarker.SEVERITY_WARNING; - marker.setAttribute(IMarker.SEVERITY, markerSeverity); - marker.setAttribute(IMarker.LINE_NUMBER, message.getLineNumber()); - } - catch (CoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - } - } - - /** - * A debugging method. A place to put break points, so that you can figure out what sort of marker - * changes are happening. - * - * @param resource - */ - public void hook(IResource resource){ -// String name = "first.test2x"; -// if (resource.getName().equals(name)){ -// String markers = Misc.listMarkers(resource); -// Tracing.log("MarkerManager has hooked: ", name); //$NON-NLS-1$ -// RuntimeException rt = new RuntimeException("hooking " + name); -// rt.printStackTrace(); -// } - } - - public Set<String> getMarkers() { - return _markers; - } - - /** - * Store the singleton for the MarkerManager. This approach is used to avoid having to synchronize the - * MarkerManager.getDefault() method. - * - * @author karasiuk - * - */ - private static class Singleton { - static MarkerManager markerManager = new MarkerManager(); - } - - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Misc.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Misc.java deleted file mode 100644 index ceafc41e5..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Misc.java +++ /dev/null @@ -1,155 +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.wst.validation.internal; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadMXBean; - -import org.eclipse.core.resources.IMarker; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceChangeEvent; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.osgi.util.NLS; - -/** - * Some miscellaneous helper methods. - * @author karasiuk - * - */ -public final class Misc { - - public static void close(InputStream in){ - if (in == null)return; - try { - in.close(); - } - catch (IOException e){ - // eat it - } - } - - public static void close(OutputStream out) { - if (out == null)return; - try { - out.close(); - } - catch (IOException e){ - // eat it - } - } - - public static boolean debugOptionAsBoolean(String option){ - String opt = Platform.getDebugOption(option); - if (opt == null)return false; - opt = opt.toLowerCase(); - if ("true".equals(opt))return true; //$NON-NLS-1$ - if ("yes".equals(opt))return true; //$NON-NLS-1$ - return false; - } - - - /** - * Answer a units appropriate string for the time. - * @param time time in nano seconds - */ - public static String getTimeNano(long time){ - if (time <= 1000)return NLS.bind(ValMessages.TimeNano, time); - if (time <= 1000000)return NLS.bind(ValMessages.TimeMicro, time/1000); - return getTimeMS(time/1000000); - } - - /** - * Answer the CPU time consumed by this thread in nano seconds. - * @return -1 if the time can not be determined. - */ - public static long getCPUTime(){ - long cpuTime = -1; - ThreadMXBean tb = ManagementFactory.getThreadMXBean(); - if (tb.isCurrentThreadCpuTimeSupported()){ - cpuTime = tb.getCurrentThreadCpuTime(); - } - return cpuTime; - } - - /** - * Answer a units appropriate string for the time. - * @param time time in milliseconds - */ - public static String getTimeMS(long time) { - if (time <= 1000)return ValMessages.TimeUnder; - if (time <= 60000)return NLS.bind(ValMessages.TimeSec, time/1000); - return NLS.bind(ValMessages.TimeMin, time/60000); - } - - /** - * Used in debugging so we can see what types of markers there are. - * @param resource - */ - public static String listMarkers(IResource resource){ - StringBuffer b = new StringBuffer(2000); - try { - IMarker[] markers = resource.findMarkers(null, true, IResource.DEPTH_ZERO); - for (IMarker m : markers){ - Object o = m.getAttribute(IMarker.MESSAGE); - if (o != null){ - b.append(o); - } - o = m.getAttribute(IMarker.SEVERITY); - if (o != null){ - b.append(", Severity="); //$NON-NLS-1$ - b.append(o); - } - b.append("; "); //$NON-NLS-1$ - } - } - catch (CoreException e){ - - } - return b.toString(); - } - - /** - * Answer true if they are the same. If they are both null then they are the same. - * @param s1 the string to compare. It can be null. - * @param s2 the string to compare. It can be null. - */ - public static boolean same(String s1, String s2){ - if (s1 == null && s2 == null)return true; - if (s1 == null)return false; - return s1.equals(s2); - } - - public static void niy(String msg){ - if (msg == null)msg = "Sorry, this function is not implemented yet"; //$NON-NLS-1$ - throw new RuntimeException(msg); - } - - /** - * Answer the type as a human readable string. This is only used for debugging. - * @param type - * @return - */ - public static String resourceChangeEventType(int type){ - StringBuffer b = new StringBuffer(200); - if ((type & IResourceChangeEvent.POST_BUILD) != 0)b.append("post_build "); //$NON-NLS-1$ - if ((type & IResourceChangeEvent.POST_CHANGE) != 0)b.append("post_change "); //$NON-NLS-1$ - if ((type & IResourceChangeEvent.PRE_BUILD) != 0)b.append("pre_build "); //$NON-NLS-1$ - if ((type & IResourceChangeEvent.PRE_CLOSE) != 0)b.append("pre_close "); //$NON-NLS-1$ - if ((type & IResourceChangeEvent.PRE_DELETE) != 0)b.append("pre_delete "); //$NON-NLS-1$ - return b.toString(); - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/NullValidator.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/NullValidator.java deleted file mode 100644 index 9f057aa03..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/NullValidator.java +++ /dev/null @@ -1,32 +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.wst.validation.internal; - -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.wst.validation.AbstractValidator; -import org.eclipse.wst.validation.ValidationResult; -import org.eclipse.wst.validation.ValidationState; - -/** - * A null validator that is used in error cases. It simply no-ops. - * @author karasiuk - * - */ -public class NullValidator extends AbstractValidator { - - @Override - public ValidationResult validate(IResource resource, int kind, ValidationState state, IProgressMonitor monitor) { - return null; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PerformanceMonitor.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PerformanceMonitor.java deleted file mode 100644 index f00e93dbd..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PerformanceMonitor.java +++ /dev/null @@ -1,192 +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.wst.validation.internal; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintWriter; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.validation.IPerformanceMonitor; -import org.eclipse.wst.validation.PerformanceCounters; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -public class PerformanceMonitor implements IPerformanceMonitor { - - private CollectionLevel _level = CollectionLevel.None; - private boolean _summaryOnly; - - /** - * Create a performance monitor. - * - * @param traceTimes - * Should the monitor be turned on? - * @param file - * Should the events be logged to a file. If this is null or the - * empty string the events will be written to stderr. Otherwise - * the events are appended to a file with this name. - * - * @param logInSeconds - * Set this to true if you want the times that are logged in the - * trace file normalized to seconds. Otherwise the default units are used, - * milliseconds for elapsed time and nanoseconds for cpu time. - */ - public static PerformanceMonitor create(boolean traceTimes, String file, boolean logInSeconds){ - PerformanceMonitor pm = null; - if (file == null || file.length() == 0)pm = new PerformanceMonitor(); - else pm = new ToFile(file, logInSeconds); - - if (traceTimes)pm.setCollectionLevel(CollectionLevel.Default); - - return pm; - } - - private PerformanceMonitor(){}; - - public CollectionLevel getCollectionLevel() { - return _level; - } - - public void setCollectionLevel(CollectionLevel level) { - _level = level; - } - - public List<PerformanceCounters> getPerformanceCounters(boolean asSummary) { - return new LinkedList<PerformanceCounters>(); - } - - - public void resetPerformanceCounters() { - } - - public boolean isCollecting() { - return _level != CollectionLevel.None; - } - - public boolean isSummaryOnly() { - return _summaryOnly; - } - - public void add(PerformanceCounters counters){ - Tracing.write(counters.toString()); - } - - public static class Counters{ - String name; - int numberInvocations; - - /** Elapsed time in milliseconds. */ - long elapsedTime; - - /** CPU time in nanoseconds, or -1 if unknown. */ - long cpuTime; - } - - public static class ToFile extends PerformanceMonitor { - - private String _fileName; - private boolean _logInSeconds; - - private PrintWriter _pw; - private static final String Comma=","; //$NON-NLS-1$ - private static DateFormat _df = new SimpleDateFormat("HH:mm:ss.SSSS"); //$NON-NLS-1$ - - private ToFile(String fileName, boolean logInSeconds){ - _fileName = fileName; - _logInSeconds = logInSeconds; - } - - @Override - public synchronized void add(PerformanceCounters pc) { - try { - PrintWriter pw = getWriter(); - pw.print(_df.format(pc.getWhen()) + Comma + - pc.getValidatorId() + Comma + pc.getNumberInvocations() + Comma); - if (_logInSeconds){ - double sec = ((double)pc.getElapsedTime()) / 1000.0; - pw.print(sec); - pw.print(Comma); - sec = ((double)pc.getCpuTime()) / 1000000000.0; - pw.print(sec); - } - else { - pw.print(pc.getElapsedTime()+Comma+pc.getCpuTime()); - } - pw.println(Comma + pc.getResourceName()); - pw.flush(); - } - catch (IOException e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - - private PrintWriter getWriter() throws IOException { - if (_pw == null){ - _pw = new PrintWriter(new FileOutputStream(_fileName, true)); - DateFormat df = DateFormat.getDateTimeInstance(); - _pw.println("# " + NLS.bind(ValMessages.LogSession, //$NON-NLS-1$ - df.format(new Date(System.currentTimeMillis())))); - if (_logInSeconds) - _pw.println("# when, id, invocation count, elapsed time (seconds), cpu time (seconds), resource"); //$NON-NLS-1$ - else - _pw.println("# when, id, invocation count, elapsed time (ms), cpu time (ns), resource"); //$NON-NLS-1$ - } - return _pw; - - } - } - - public static class Collecting extends PerformanceMonitor { - private List<PerformanceCounters> _counters = new LinkedList<PerformanceCounters>(); - - public void add(PerformanceCounters counters){ - _counters.add(counters); - } - - public List<PerformanceCounters> getPerformanceCounters(boolean asSummary) { - if (asSummary){ - Map<String, Counters> map = new HashMap<String, Counters>(40); - for (PerformanceCounters pc : _counters){ - Counters c = map.get(pc.getValidatorId()); - if (c == null){ - c = new Counters(); - c.name = pc.getValidatorName(); - map.put(pc.getValidatorId(), c); - } - c.numberInvocations += pc.getNumberInvocations(); - c.elapsedTime += pc.getElapsedTime(); - if (pc.getCpuTime() != -1)c.cpuTime += pc.getCpuTime(); - else c.cpuTime = -1; - } - List<PerformanceCounters> list = new LinkedList<PerformanceCounters>(); - for (Map.Entry<String, Counters> me : map.entrySet()){ - Counters c = me.getValue(); - list.add(new PerformanceCounters(me.getKey(), c.name, null, c.numberInvocations, c.elapsedTime, c.cpuTime)); - } - return list; - } - return _counters; - } - - public void resetPerformanceCounters() { - _counters.clear(); - } - - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PrefConstants.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PrefConstants.java deleted file mode 100644 index 3bac075dc..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PrefConstants.java +++ /dev/null @@ -1,116 +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.wst.validation.internal; - -/** - * The constants that are used in the preference store so save the validator configurations. - * <p> - * The entries in the preference hierarchy are organized something like this: - * <pre> - * /instance/frame-work-id/saveAuto=true|false - * /instance/frame-work-id/suspend=true|false - * /instance/frame-work-id/vf.version=2 - * /instance/frame-work-id/filters/val-id/build=true|false - * /instance/frame-work-id/filters/val-id/manual=true|false - * /instance/frame-work-id/filters/val-id/version=someNumber - * /instance/frame-work-id/filters/val-id/groups/0/type=include|exclude - * /instance/frame-work-id/filters/val-id/groups/0/rules/0/type=file|fileext|projectNature|... - * /instance/frame-work-id/filters/val-id/groups/0/rules/0/pattern=... - * /instance/frame-work-id/filters/val-id/groups/0/rules/1/type=file|fileext|projectNature|... - * /instance/frame-work-id/filters/val-id/groups/0/rules/1/pattern=... - * </pre> - * <p> - * New approach - * <pre> - * vals/val-id/global=TF[version][len]delegate-id - * vals/val-id/groups=[groups] - * </pre> - * - * - * @author karasiuk - * - */ -public interface PrefConstants { - - /** filters - node where all the filters are saved. */ - String filters = "filters"; //$NON-NLS-1$ - - /** build - is the validator enabled for builds? */ - String build = "build"; //$NON-NLS-1$ - - /** delegate - the delegating implementation to use */ - String delegate = "delegate"; //$NON-NLS-1$ - - /** disabled - the list of disabled resources in the project. */ - String disabled = "disabled"; //$NON-NLS-1$ - - /** exactMatch - must the content type match exactly? */ - String exactMatch = "exactMatch"; //$NON-NLS-1$ - - /** manual - is the validator enabled for manual validation? */ - String manual = "manual"; //$NON-NLS-1$ - - /** msgs - node where all the message severity mappings are stored. */ - String msgs = "msgs"; //$NON-NLS-1$ - - /** - * version - version of the filter definition. This is something that a client can use to keep track - * of changes that they might make to their validation extension. - */ - String version = "version"; //$NON-NLS-1$ - - /** vf.version - version of the validation framework. */ - String frameworkVersion = "vf.version"; //$NON-NLS-1$ - - /** groups - filter group. */ - String groups = "groups"; //$NON-NLS-1$ - - /** type - type of group, either include or exclude. */ - String type = "type"; //$NON-NLS-1$ - - /** type - the type of rule. */ - String ruleType = "type"; //$NON-NLS-1$ - - /** rules - a filter rule. */ - String rules = "rules"; //$NON-NLS-1$ - - /** pattern - the pattern part of the rule. */ - String pattern = "pattern"; //$NON-NLS-1$ - - /** saveAuto - can we save all the resources automatically? true/false */ - String saveAuto = "saveAuto"; //$NON-NLS-1$ - - /** stateTS - plug-in state time stamp */ - String stateTS = "stateTS"; //$NON-NLS-1$ - - /** suspend - suspend all validation? true/false */ - String suspend = "suspend"; //$NON-NLS-1$ - - /** case - is this case sensitive? */ - String caseSensitive = "case"; //$NON-NLS-1$ - - /** fileType - the type of file, see FilterRule.File */ - String fileType = "fileType"; //$NON-NLS-1$ - - /** confirmDialog - should we show a confirmation dialog when doing a manual validation? */ - String confirmDialog = "confirmDialog"; //$NON-NLS-1$ - - /** override - should we show projects to override the global preferences? */ - String override = "override"; //$NON-NLS-1$ - - /** vals - the validators are grouped under this node. */ - String vals = "vals"; //$NON-NLS-1$ - - /** global - some global validation settings. */ - String global = "global"; //$NON-NLS-1$ - - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PreferencesWrapper.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PreferencesWrapper.java deleted file mode 100644 index 0f3a5e7e0..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/PreferencesWrapper.java +++ /dev/null @@ -1,431 +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.wst.validation.internal; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; - -import org.eclipse.core.resources.IProject; -import org.eclipse.wst.validation.ValidationFramework; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; -import org.osgi.service.prefs.BackingStoreException; -import org.osgi.service.prefs.Preferences; - -/** - * The subset of the IEclipsePreferences interface that the framework needs to - * be able to persist preferences. - * @author karasiuk - * - */ -public abstract class PreferencesWrapper { - - private static final WrapperManger _manager = new WrapperManger(); - - /** - * Answer the preferences for the project. If project is null answer the global preferences. - * @param project - * @param persistent if null the default preferences are returned, if True the persisted - * preferences are return and if False the transient preferences are returned. - * @return - */ - public static PreferencesWrapper getPreferences(IProject project, Boolean persistent){ - return _manager.get(project, persistent); - } - - /** - * These are the names of the node entries. - * @return - * @throws BackingStoreException - */ - public abstract String[] childrenNames() throws BackingStoreException; - - public void flush() throws BackingStoreException { - } - - public abstract boolean getBoolean(String key, boolean def); - - public abstract String get(String key, String def); - - public abstract int getInt(String key, int def); - - public abstract long getLong(String key, long def); - - public abstract String[] keys() throws BackingStoreException; - - public boolean isPersistent(){ - return false; - } - - public boolean isTransient(){ - return false; - } - - public abstract void put(String key, String value); - - public abstract void putBoolean(String key, boolean value); - - public abstract void putLong(String key, long value); - - public abstract void putInt(String key, int value); - - /** - * Unlike the more sophisticated org.osgi.service.prefs.Preferences support, - * this is currently limited to simple node names. - */ - public abstract PreferencesWrapper node(String nodeName); - - public abstract boolean nodeExists(); - - public abstract boolean nodeExists(String pathName) throws BackingStoreException; - - public abstract void removeNode() throws BackingStoreException; - - -public final static class PreferencesWrapperPersistent extends PreferencesWrapper { - - private final Preferences _preferences; - - public PreferencesWrapperPersistent(Preferences preferences){ - _preferences = preferences; - } - - @Override - public String[] childrenNames() throws BackingStoreException { - return _preferences.childrenNames(); - } - - public void flush() throws BackingStoreException { - _preferences.flush(); - } - - @Override - public String get(String key, String def) { - return _preferences.get(key, def); - } - - @Override - public boolean getBoolean(String key, boolean def) { - return _preferences.getBoolean(key, def); - } - - @Override - public int getInt(String key, int def) { - return _preferences.getInt(key, def); - } - - @Override - public long getLong(String key, long def) { - return _preferences.getLong(key, def); - } - - @Override - public String[] keys() throws BackingStoreException { - return _preferences.keys(); - } - - @Override - public boolean isPersistent() { - return true; - } - - @Override - public void put(String key, String value) { - _preferences.put(key, value); - } - - @Override - public PreferencesWrapper node(String path) { - Preferences prefs = _preferences.node(path); - return new PreferencesWrapperPersistent(prefs); - } - - @Override - public boolean nodeExists() { - try { - return nodeExists(""); //$NON-NLS-1$ - } - catch (BackingStoreException e){ - - } - return false; - } - - @Override - public boolean nodeExists(String pathName) throws BackingStoreException { - return _preferences.nodeExists(pathName); - } - - public void putBoolean(String key, boolean value) { - _preferences.putBoolean(key, value); - } - - public void putLong(String key, long value){ - _preferences.putLong(key, value); - } - - @Override - public void putInt(String key, int value) { - _preferences.putInt(key, value); - } - - @Override - public void removeNode() throws BackingStoreException { - _preferences.removeNode(); - } -} - -public final static class PreferencesWrapperTransient extends PreferencesWrapper { - - private final PreferencesWrapperTransient _parent; - private final Map<String, String> _children = Collections.synchronizedMap(new HashMap<String, String>(10)); - private final Map<String, PreferencesWrapperTransient> _nodes = Collections.synchronizedMap(new HashMap<String, PreferencesWrapperTransient>(10)); - - public PreferencesWrapperTransient(PreferencesWrapperTransient parent){ - _parent = parent; - } - - public PreferencesWrapperTransient(PreferencesWrapper pw, PreferencesWrapperTransient parent) { - _parent = parent; - try { - for (String key : pw.keys()){ - put(key, pw.get(key, null)); - } - - - for (String nodeName : pw.childrenNames()){ - PreferencesWrapper p = pw.node(nodeName); - PreferencesWrapperTransient pwt = new PreferencesWrapperTransient(p, this); - _nodes.put(nodeName, pwt); - } - } - catch (BackingStoreException e){ - - } - } - - @Override - public String[] childrenNames() throws BackingStoreException { - Set<String> keys = _nodes.keySet(); - String names[] = new String[keys.size()]; - keys.toArray(names); - return names; - } - - @Override - public String get(String key, String def) { - String value = _children.get(key); - if (value != null)return value; - return def; - } - - @Override - public boolean getBoolean(String key, boolean def) { - String value = _children.get(key); - if (value == null)return def; - value = value.toLowerCase(); - if ("true".equals(value))return true; //$NON-NLS-1$ - if ("false".equals(value))return false; //$NON-NLS-1$ - return def; - } - - @Override - public int getInt(String key, int def) { - String value = _children.get(key); - if (value == null)return def; - try { - return Integer.parseInt(value); - } - catch (NumberFormatException e){ - } - return def; - } - - @Override - public long getLong(String key, long def) { - String value = _children.get(key); - if (value == null)return def; - try { - return Long.parseLong(value); - } - catch (NumberFormatException e){ - } - return def; - } - - @Override - public boolean isTransient() { - return true; - } - - @Override - public synchronized String[] keys() throws BackingStoreException { - String[] keys = new String[_children.size()]; - _children.keySet().toArray(keys); - return keys; - } - - @Override - public synchronized PreferencesWrapper node(String name) { - PreferencesWrapperTransient pw = _nodes.get(name); - if (pw != null)return pw; - pw = new PreferencesWrapperTransient(this); - _nodes.put(name, pw); - return pw; - } - - @Override - public boolean nodeExists() { - return true; - } - - @Override - public boolean nodeExists(String key) throws BackingStoreException { - PreferencesWrapperTransient pw = _nodes.get(key); - if (pw != null)return true; - return false; - } - - @Override - public void put(String key, String value) { - _children.put(key, value); - } - - @Override - public void putBoolean(String key, boolean bool) { - String value = bool ? "true" : "false"; //$NON-NLS-1$//$NON-NLS-2$ - _children.put(key, value); - } - - @Override - public void putInt(String key, int value) { - _children.put(key, String.valueOf(value)); - } - - @Override - public void putLong(String key, long value) { - _children.put(key, String.valueOf(value)); - } - - @Override - public void removeNode() throws BackingStoreException { - if (_parent == null)return; - _parent.removeNode(this); - } - - private synchronized void removeNode(PreferencesWrapperTransient node){ - String key = null; - for (Map.Entry<String, PreferencesWrapperTransient> me : _nodes.entrySet()){ - if (me.getValue().equals(node)){ - key = me.getKey(); - break; - } - } - if (key != null)_nodes.remove(key); - } -} - -private final static class WrapperManger implements IProjectChangeListener { - - private final Map<IProject, PreferencesWrapper> _map = new HashMap<IProject, PreferencesWrapper>(20); - private final AtomicReference<PreferencesWrapper> _global = new AtomicReference<PreferencesWrapper>(); - - private WrapperManger(){ - EventManager.getManager().addProjectChangeListener(this); - } - - /** - * Currently this object never goes away, but if that was ever to change then we would need to dispose it. - */ - @Override - protected void finalize() throws Throwable { - dispose(); - } - - public void dispose(){ - EventManager.getManager().removeProjectChangeListener(this); - } - - public PreferencesWrapper get(IProject project, Boolean persistent) { - if (project == null)return globalPreferences(persistent); - PreferencesWrapper pw = null; - synchronized(_map){ - pw = _map.get(project); - } - - if (pw != null && (persistent == null || persistent == pw.isPersistent()))return pw; - - if (pw == null)pw = new PreferencesWrapperPersistent(ValidationPlugin.getPreferences(project)); - if (persistent != null && persistent && pw.isTransient())pw = new PreferencesWrapperPersistent(ValidationPlugin.getPreferences(project)); - if (persistent != null && !persistent && pw.isPersistent())pw = new PreferencesWrapperTransient(pw, null); - - synchronized(_map){ - _map.put(project, pw); - } - - return pw; - } - - /** - * Answer the appropriate global preferences. - * - * @param persistent - * If null then answer the current saved global preferences, - * creating a new persistent one if there is none. If True, - * then ensure that the preferences are persistent. If False, - * ensure that the preferences are transient. - * @return - */ - private PreferencesWrapper globalPreferences(Boolean persistent) { - PreferencesWrapper pw = _global.get(); - - while(pw == null){ - PreferencesWrapper newPW = createGlobal(persistent); - if (_global.compareAndSet(null, newPW))pw = newPW; - else pw = _global.get(); - } - - while (persistent != null && !persistent && !pw.isTransient()){ - PreferencesWrapper newPW = new PreferencesWrapperTransient(pw, null); - if (_global.compareAndSet(pw, newPW))pw = newPW; - else pw = _global.get(); - } - - while (persistent != null && persistent && !pw.isPersistent()){ - PreferencesWrapper newPW = new PreferencesWrapperPersistent(ValidationFramework.getDefault().getPreferenceStore()); - if (_global.compareAndSet(pw, newPW))pw = newPW; - else pw = _global.get(); - } - return pw; - } - - private PreferencesWrapper createGlobal(Boolean persistent){ - PreferencesWrapper pw = new PreferencesWrapperPersistent(ValidationFramework.getDefault().getPreferenceStore()); - if (persistent == null || persistent)return pw; - return new PreferencesWrapperTransient(pw, null); - } - - public void projectChanged(IProject project, int type) { - int interested = IProjectChangeListener.ProjectClosed | IProjectChangeListener.ProjectDeleted; - if ((type & interested) != 0){ - synchronized (_map) { - _map.remove(project); - } - } - - } - -} - - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ProjectUnavailableError.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ProjectUnavailableError.java deleted file mode 100644 index 03e2b65c7..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ProjectUnavailableError.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 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.wst.validation.internal; - -import org.eclipse.core.resources.IProject; - -/** - * This internal error is used to signal that a project is now unavailable. - * <p> - * We could be in the middle of validating a large project, and the project could be closed. - * This error is used to "exit" the validation framework. - * <p> - * This is an error rather than a runtime exception, because some parts of Eclipse like to - * trap RuntimeExceptions and log them. - * @author karasiuk - * - */ -public class ProjectUnavailableError extends Error { - - private IProject _project; - - private static final long serialVersionUID = 200801281118L; - - public ProjectUnavailableError(IProject project){ - super(); - _project = project; - } - - public IProject getProject() { - return _project; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ResourceUnavailableError.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ResourceUnavailableError.java deleted file mode 100644 index 9543670a7..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ResourceUnavailableError.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 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.wst.validation.internal; - -import org.eclipse.core.resources.IResource; - -/** - * This internal error is used to signal that a resource is now unavailable. - * <p> - * This error is used to "exit" the validation framework. - * <p> - * This is an error rather than a runtime exception, because some parts of Eclipse like to - * trap RuntimeExceptions and log them. - * @author karasiuk - * - */ -public class ResourceUnavailableError extends Error { - - private static final long serialVersionUID = 200801290853L; - - private IResource _resource; - - public ResourceUnavailableError(IResource resource){ - super(); - _resource = resource; - } - - public IResource getResource() { - return _resource; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Serializer.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Serializer.java deleted file mode 100644 index 22da768bd..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Serializer.java +++ /dev/null @@ -1,48 +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.wst.validation.internal; - -/** - * A simple encoder that knows how to convert booleans, integers and strings, into a single string. - * - * @see Deserializer - * @author karasiuk - * - */ -public class Serializer { - private StringBuffer _buffer; - - public Serializer(int size){ - _buffer = new StringBuffer(size); - } - - public void put(boolean bool){ - _buffer.append(bool ? 'T' : 'F'); - } - - public void put(String string){ - put(string.length()); - _buffer.append(string); - } - - public void put(int anInt){ - String s = String.valueOf(anInt); - int len = s.length(); - _buffer.append(len-1); - _buffer.append(s); - } - - @Override - public String toString() { - return _buffer.toString(); - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/SummaryReporter.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/SummaryReporter.java deleted file mode 100644 index 5a19332c7..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/SummaryReporter.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 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.wst.validation.internal; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.wst.validation.internal.operations.WorkbenchReporter; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; - -/** - * This class extends the workbench reporter by capturing some summary information about any added - * messages. - * @author karasiuk - * - */ -public class SummaryReporter extends WorkbenchReporter { - - private int _severityHigh; - private int _severityNormal; - private int _severityLow; - - public SummaryReporter(IProject project, IProgressMonitor monitor) { - super(project, monitor); - } - - @Override - public void addMessage(IValidator validator, IMessage message) { - super.addMessage(validator, message); - switch (message.getSeverity()){ - case IMessage.HIGH_SEVERITY: - _severityHigh++; - break; - case IMessage.NORMAL_SEVERITY: - _severityNormal++; - break; - case IMessage.LOW_SEVERITY: - _severityLow++; - break; - } - } - - public int getSeverityHigh() { - return _severityHigh; - } - - public int getSeverityNormal() { - return _severityNormal; - } - - public int getSeverityLow() { - return _severityLow; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Tracing.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Tracing.java deleted file mode 100644 index 77e49cb65..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/Tracing.java +++ /dev/null @@ -1,208 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 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.wst.validation.internal; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IResourceDeltaVisitor; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -/** - * Control the tracing that this plug-in performs. This is used for service. - * @author karasiuk - * - */ -public final class Tracing { - - private final static DateFormat _df = new SimpleDateFormat("HH:mm:ss.SSSS"); //$NON-NLS-1$ - private final static boolean _isLogging = ValidationPlugin.getPlugin().isDebugging(); - private final static boolean _traceMatches = Misc.debugOptionAsBoolean(DebugConstants.TraceMatches); - private final static boolean _traceV1 = Misc.debugOptionAsBoolean(DebugConstants.TraceV1); - private final static String _extraValDetail = Platform.getDebugOption(DebugConstants.ExtraValDetail); - private final static int _tracingLevel; - - private final static String _filter = Platform.getDebugOption(DebugConstants.FilterAllExcept); - - static { - String traceLevel = Platform.getDebugOption(DebugConstants.TraceLevel); - int level = 0; - if (traceLevel != null){ - try { - level = Integer.parseInt(traceLevel); - } - catch (Exception e){ - } - } - _tracingLevel = level; - } - - /** - * Answer true if the filters allow this validator to be enabled. Normally this method will answer true. - * It is only when filters are activated via the debugging options, that this method might return false. - * This is used to aid in debugging by making it look like only one validator has been registered. - * - * @param validatorId the validator id. - * @return true if the validator should be registered via an extension point. - */ - public static boolean isEnabled(String validatorId){ - if (_filter == null || _filter.length() == 0)return true; - return (_filter.equals(validatorId)); - } - - /** - * Are we in logging/debugging mode? - */ - public static boolean isLogging(){ - return _isLogging; - } - - /** - * Answer true if we are in logging mode, and if the current logging level is greater than or - * equal to level. - * @param level The logging level that we are testing. The higher the level the more verbose - * the tracing. - */ - public static boolean isLogging(int level){ - if (_isLogging){ - return _tracingLevel >= level; - } - return false; - } - - public static boolean isTraceMatches(){ - return _traceMatches; - } - - public static boolean isTraceV1(){ - return _traceV1; - } - - public static boolean matchesExtraDetail(String validatorId){ - if (_extraValDetail == null)return false; - return _extraValDetail.equals(validatorId); - } - - /** - * Write a line to the console for debugging, if in debugging mode. - * @param line - */ - public static void log(String line){ - if (isLogging())write(line); - } - - public static void log(Object... parts){ - if (isLogging()){ - StringBuffer b = new StringBuffer(200); - for (Object p : parts)b.append(p); - write(b.toString()); - } - } - - /** - * Write a line to the log. Include a time stamp with the line. - * @param line - */ - public static void write(String line){ - System.err.println(timestampIt(line)); - } - - public static String timestampIt(String line){ - Date date = new Date(); - String thread = Thread.currentThread().getName(); - return _df.format(date) + " " + thread + " " + line; //$NON-NLS-1$//$NON-NLS-2$ - } - - /** - * If we are in logging mode, log the item, and then reset the string buffer. - */ - public static void log(StringBuffer b){ - log(b.toString()); - b.setLength(0); - } - - /** - * This method doesn't do anything, and will be removed. - * - * @deprecated - */ - public static void setForceLogging(boolean forceLogging) { - } - - /** - * Log up to maxNumber deltas to the log. - * @param delta The deltas to log. - * @param maxNumber The maximum number of deltas to log. - */ - public static void logResourceDeltas(IResourceDelta delta, int maxNumber){ - if (!isLogging())return; - if (delta == null)Tracing.log(" ResourceDelta: null"); //$NON-NLS-1$ - else { - DeltaLogger logger = new DeltaLogger(maxNumber); - try { - delta.accept(logger); - if (logger.getCount() == 0)Tracing.log(" ResourceDelta: no deltas"); //$NON-NLS-1$ - } - catch (CoreException e){ - // eat it - } - } - } - - /** - * A debugging class that prints out some resource delta's. - * @author karasiuk - * - */ - private final static class DeltaLogger implements IResourceDeltaVisitor { - - private final int _max; - private int _count; - public int getCount() { - return _count; - } - - private StringBuffer _b = new StringBuffer(200); - - public DeltaLogger(int max){ - _max = max; - } - - public boolean visit(IResourceDelta delta) throws CoreException { - if (_count++ > _max)return false; - int kind = delta.getKind(); - String type = "unknown"; //$NON-NLS-1$ - switch (kind){ - case IResourceDelta.ADDED: - type = "Added"; //$NON-NLS-1$ - break; - case IResourceDelta.CHANGED: - type = "Changed"; //$NON-NLS-1$ - break; - case IResourceDelta.REMOVED: - type = "Removed"; //$NON-NLS-1$ - break; - } - _b.append(" ResourceDelta "); //$NON-NLS-1$ - _b.append(type); - _b.append(' '); - _b.append(delta.getResource()); - Tracing.log(_b); - return true; - } - - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValBuilderJob.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValBuilderJob.java deleted file mode 100644 index 5aafeee98..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValBuilderJob.java +++ /dev/null @@ -1,345 +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.wst.validation.internal; - -import java.util.LinkedList; -import java.util.Queue; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IResourceDeltaVisitor; -import org.eclipse.core.resources.IResourceProxy; -import org.eclipse.core.resources.IResourceProxyVisitor; -import org.eclipse.core.resources.IResourceVisitor; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.resources.WorkspaceJob; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubMonitor; -import org.eclipse.wst.validation.DependentResource; -import org.eclipse.wst.validation.Friend; -import org.eclipse.wst.validation.IDependencyIndex; -import org.eclipse.wst.validation.ValidationEvent; -import org.eclipse.wst.validation.ValidationFramework; -import org.eclipse.wst.validation.ValidationState; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.internal.model.IValidatorVisitor; -import org.eclipse.wst.validation.internal.operations.ValidationBuilder; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - - -/** - * Run all the v2 validators through this job. - * <p> - * This is the main class for supporting build based validation. When triggered it looks at all of the - * resource changes and determines what needs to be validated. - * </p> - * @author karasiuk - * - */ -public final class ValBuilderJob extends WorkspaceJob { - - private static ValBuilderJob _job; - private static Queue<ValidationRequest> _work = new LinkedList<ValidationRequest>(); - - private final ValOperation _operation = new ValOperation(); - - /** The types of changes we are interested in. */ - private final static int InterestedFlags = IResourceDelta.CONTENT | IResourceDelta.ENCODING | - IResourceDelta.MOVED_FROM | IResourceDelta.MOVED_TO; - - public static synchronized void validateProject(IProject project, IResourceDelta delta, int buildKind){ - ValidationRequest request = new ValidationRequest(project, delta, buildKind); - if (_job == null){ - _job = new ValBuilderJob(); - _job.add(request); - _job.schedule(); - } - else { - _job.add(request); - } - } - - private static synchronized ValidationRequest getRequest(){ - ValidationRequest request = _work.poll(); - if (request == null){ - _job = null; - } - return request; - } - - /** - * Each validation run is done in it's own job. - * - * @param project the project that is being validated - * @param delta the delta that is being validated. This may be null, in which case we do a - * full validation of the project. - * - * @param buildKind the kind of build. - * @see org.eclipse.core.resources.IncrementalProjectBuilder#AUTO_BUILD - * @see org.eclipse.core.resources.IncrementalProjectBuilder#CLEAN_BUILD - * @see org.eclipse.core.resources.IncrementalProjectBuilder#FULL_BUILD - * @see org.eclipse.core.resources.IncrementalProjectBuilder#INCREMENTAL_BUILD - * - * @param operation some global context for the validation operation - * - */ - private ValBuilderJob(){ - super(ValMessages.JobName); - } - - private void add(ValidationRequest request){ - _work.add(request); - } - - @Override - public boolean belongsTo(Object family) { - if (family == ResourcesPlugin.FAMILY_MANUAL_BUILD)return true; - if (family == ValidationBuilder.FAMILY_VALIDATION_JOB){ - return true; - } - - return super.belongsTo(family); - } - - @Override - public IStatus runInWorkspace(IProgressMonitor monitor) { - Tracing.log("ValBuilderJob-01: Starting"); //$NON-NLS-1$ - - try { - startingValidation(monitor); - - ValidationRequest request = getRequest(); - while(request != null){ - run(request, monitor); - request = getRequest(); - } - } - finally { - finishingValidation(monitor); - } - - Tracing.log("ValBuilderJob-02: Finished"); //$NON-NLS-1$ - return Status.OK_STATUS; - } - - private void startingValidation(IProgressMonitor monitor) { - IValidatorVisitor startingVisitor = new IValidatorVisitor(){ - - public void visit(Validator validator, IProject project, ValType valType, - ValOperation operation, IProgressMonitor monitor) { - - validator.validationStarting(project, operation.getState(), monitor); - } - }; - - ValManager.getDefault().accept(startingVisitor, null, ValType.Build, getOperation(), monitor); - } - - private void finishingValidation(IProgressMonitor monitor) { - - IValidatorVisitor finishedVisitor = new IValidatorVisitor(){ - - public void visit(Validator validator, IProject project, ValType valType, - ValOperation operation, IProgressMonitor monitor) { - - validator.validationFinishing(project, operation.getState(), monitor); - } - }; - ValManager.getDefault().accept(finishedVisitor, null, ValType.Build, getOperation(), monitor); - } - - private void run(ValidationRequest request, IProgressMonitor monitor){ - setName(ValMessages.JobName + " " + request.getProject().getName()); //$NON-NLS-1$ - try { - IValidatorVisitor startingVisitor = new IValidatorVisitor(){ - - public void visit(Validator validator, IProject project, ValType valType, - ValOperation operation, IProgressMonitor monitor) { - - validator.validationStarting(project, operation.getState(), monitor); - } - }; - - ValManager.getDefault().accept(startingVisitor, request.getProject(), ValType.Build, getOperation(), monitor); - - if (request.getDelta() == null)fullBuild(request, monitor); - else deltaBuild(request, monitor); - - - } - catch (ProjectUnavailableError e){ - ValidationPlugin.getPlugin().handleProjectUnavailableError(e); - } - catch (ResourceUnavailableError e){ - ValidationPlugin.getPlugin().handleResourceUnavailableError(e); - } - catch (CoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - finally { - IValidatorVisitor finishedVisitor = new IValidatorVisitor(){ - - public void visit(Validator validator, IProject project, ValType valType, - ValOperation operation, IProgressMonitor monitor) { - - validator.validationFinishing(project, operation.getState(), monitor); - } - }; - ValManager.getDefault().accept(finishedVisitor, request.getProject(), ValType.Build, getOperation(), monitor); - } - - } - - private void deltaBuild(ValidationRequest request, IProgressMonitor monitor) throws CoreException { - ResourceCounter counter = new ResourceCounter(); - request.getDelta().accept(counter); - SubMonitor subMonitor = SubMonitor.convert(monitor, counter.getCount()); - Visitor vistitor = new Visitor(request, subMonitor, monitor, getOperation()); - request.getDelta().accept(vistitor); - } - - private void fullBuild(ValidationRequest request, IProgressMonitor monitor) throws CoreException { - ResourceCounter counter = new ResourceCounter(); - request.getProject().accept(counter, 0); - SubMonitor subMonitor = SubMonitor.convert(monitor, counter.getCount()); - Visitor vistitor = new Visitor(request, subMonitor, monitor, getOperation()); - request.getProject().accept(vistitor); - - } - - private ValOperation getOperation(){ - return _operation; - } - - static final class ResourceCounter implements IResourceProxyVisitor, IResourceDeltaVisitor { - - private int _count; - - public int getCount() { - return _count; - } - - public boolean visit(IResourceProxy proxy) throws CoreException { - _count++; - return true; - } - - public boolean visit(IResourceDelta delta) throws CoreException { - _count++; - return true; - } - } - - static final class ValidationRequest { - /** The project that is being built. */ - private final IProject _project; - - /** The resource delta that triggered the build, it will be null for a full build. */ - private final IResourceDelta _delta; - - /** - * The kind of build. - * - * @see org.eclipse.core.resources.IncrementalProjectBuilder - */ - private final int _buildKind; - - public ValidationRequest(IProject project, IResourceDelta delta, int buildKind){ - _project = project; - _delta = delta; - _buildKind = buildKind; - } - - public IProject getProject() { - return _project; - } - - public IResourceDelta getDelta() { - return _delta; - } - - public int getBuildKind() { - return _buildKind; - } - } - - private final static class Visitor implements IResourceDeltaVisitor, IResourceVisitor{ - - private final ValidationRequest _request; - private final SubMonitor _subMonitor; - private final IProgressMonitor _monitor; - private final ValOperation _operation; - - public Visitor(ValidationRequest request, SubMonitor subMonitor, IProgressMonitor monitor, ValOperation operation){ - _request = request; - _subMonitor = subMonitor; - _monitor = monitor; - _operation = operation; - } - - public boolean visit(IResource resource) throws CoreException { - try { - if (DisabledResourceManager.getDefault().isDisabled(resource)){ - MarkerManager.getDefault().deleteMarkers(resource, _operation.getStarted(), IResource.DEPTH_INFINITE); - return false; - } - ValManager.getDefault().validate(_request.getProject(), resource, IResourceDelta.NO_CHANGE, ValType.Build, - _request.getBuildKind(), _operation, _subMonitor.newChild(1)); - } - catch (ResourceUnavailableError e){ - if (Tracing.isLogging())Tracing.log("ValBuilderJob-02: " + e.toString()); //$NON-NLS-1$ - return false; - } - return true; - } - - @SuppressWarnings("deprecation") - public boolean visit(IResourceDelta delta) throws CoreException { - IResource resource = delta.getResource(); - if (DisabledResourceManager.getDefault().isDisabled(resource)){ - MarkerManager.getDefault().deleteMarkers(resource, _operation.getStarted(), IResource.DEPTH_INFINITE); - return false; - } - int kind = delta.getKind(); - boolean isChanged = (kind & IResourceDelta.CHANGED) != 0; - if (isChanged && (delta.getFlags() & InterestedFlags) == 0)return true; - - if ((kind & (IResourceDelta.ADDED | IResourceDelta.CHANGED)) != 0){ - ValManager.getDefault().validate(_request.getProject(), resource, delta.getKind(), ValType.Build, - _request.getBuildKind(), _operation, _subMonitor.newChild(1)); - } - - IDependencyIndex index = ValidationFramework.getDefault().getDependencyIndex(); - if (index.isDependedOn(resource)){ - MarkerManager mm = MarkerManager.getDefault(); - for (DependentResource dr : index.get(resource)){ - Validator val = dr.getValidator(); - if (Friend.shouldValidate(val, dr.getResource(), ValType.Build, new ContentTypeWrapper())){ - _operation.getState().put(ValidationState.TriggerResource, resource); - ValidationEvent event = new ValidationEvent(dr.getResource(), IResourceDelta.NO_CHANGE, delta); - if (val.shouldClearMarkers(event))mm.clearMarker(dr.getResource(), val); - ValManager.getDefault().validate(val, _operation, dr.getResource(), - IResourceDelta.NO_CHANGE, _monitor, event); - } - } - } - - return true; - } - - - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValConstants.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValConstants.java deleted file mode 100644 index ab2aebfea..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValConstants.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 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.wst.validation.internal; - -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -public interface ValConstants { - /** problem marker for version 2 of the validation framework. */ - String ProblemMarker = ValidationPlugin.PLUGIN_ID +".problemmarker2"; //$NON-NLS-1$ - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValManager.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValManager.java deleted file mode 100644 index 9214a1918..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValManager.java +++ /dev/null @@ -1,1291 +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.wst.validation.internal; - -import java.lang.reflect.InvocationTargetException; -import java.util.BitSet; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceStatus; -import org.eclipse.core.resources.IResourceVisitor; -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.ISafeRunnable; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.SafeRunner; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubMonitor; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.common.project.facet.core.FacetedProjectFramework; -import org.eclipse.wst.common.project.facet.core.events.IFacetedProjectEvent; -import org.eclipse.wst.common.project.facet.core.events.IFacetedProjectListener; -import org.eclipse.wst.validation.Friend; -import org.eclipse.wst.validation.IPerformanceMonitor; -import org.eclipse.wst.validation.IValidatorGroupListener; -import org.eclipse.wst.validation.PerformanceCounters; -import org.eclipse.wst.validation.ValidationEvent; -import org.eclipse.wst.validation.ValidationFramework; -import org.eclipse.wst.validation.ValidationResult; -import org.eclipse.wst.validation.ValidationState; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.internal.model.GlobalPreferences; -import org.eclipse.wst.validation.internal.model.GlobalPreferencesValues; -import org.eclipse.wst.validation.internal.model.IValidatorVisitor; -import org.eclipse.wst.validation.internal.model.ProjectPreferences; -import org.eclipse.wst.validation.internal.operations.ManualValidatorsOperation; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; -import org.osgi.service.prefs.BackingStoreException; - -/** - * A central place to keep track of all the validators. - * @author karasiuk - * - */ -public final class ValManager implements IValChangedListener, IFacetedProjectListener, IProjectChangeListener { - - /** - * Projects may be allowed to override the global validation settings. If that is the case then those - * project specific settings are saved here. If the key exists, but the value is null, then that - * means that the project has been checked and it does not have any specific settings. - */ - private final Map<IProject, ProjectPreferences> _projectPreferences = - Collections.synchronizedMap(new HashMap<IProject, ProjectPreferences>(50)); - - private final AtomicReference<GlobalPreferences> _globalPreferences = new AtomicReference<GlobalPreferences>(); - - /** - * This number increases each time any of the validation configurations change. It is used to determine - * if information that we have cached in the ValProperty is stale or not. This starts off at zero, each time - * the workbench is started. - */ - private final AtomicInteger _configNumber = new AtomicInteger(); - - private final ValidatorIdManager _idManager = new ValidatorIdManager(); - private final ValidatorCache _cache = new ValidatorCache(); - - private static final QualifiedName StatusBuild = new QualifiedName(ValidationPlugin.PLUGIN_ID, "sb"); //$NON-NLS-1$ - private static final QualifiedName StatusManual = new QualifiedName(ValidationPlugin.PLUGIN_ID, "sm"); //$NON-NLS-1$ - - - public static ValManager getDefault(){ - return Singleton.valManager; - } - - private ValManager(){ - ValPrefManagerGlobal.getDefault().addListener(this); - ValPrefManagerProject.addListener(this); - FacetedProjectFramework.addListener(this, IFacetedProjectEvent.Type.PROJECT_MODIFIED); - EventManager.getManager().addProjectChangeListener(this); - } - - /** - * This needs to be called if the ValManager is ever deleted. - */ - public void dispose(){ - // currently nobody calls this method, because this instance is never removed, but the method is - // here for completeness none the less. - ValPrefManagerGlobal.getDefault().removeListener(this); - ValPrefManagerProject.removeListener(this); - FacetedProjectFramework.removeListener(this); - EventManager.getManager().removeProjectChangeListener(this); - } - - /** - * Answer all the registered validators. If you are planning on making changes to the validators, - * and then saving them in a preference store then you probably want the getValidatorsCopy method. - * Because if you make changes to the original validators, and since we only save differences, - * there won't be any differences. - * - * @return Answer the validators in name sorted order. Answer an empty array if there are no validators. - * - * @see #getValidatorsCopy() - */ - public Validator[] getValidators(){ - return getValidators(null); - } - - /** - * Answer copies of all the registered validators. If you are going to be making changes to the validators - * and then saving them backing into the preference store, then this is the method to use. - * - * @return Answer an empty array if there are no validators. - */ - public Validator[] getValidatorsCopy(){ - Validator[] orig = getValidators(); - Validator[] copy = new Validator[orig.length]; - for (int i=0; i<orig.length; i++)copy[i] = orig[i].copy(); - return copy; - } - - /** - * Answer all the validators for the given project. - * <p> - * Individual projects may override the global validation preference - * settings. If the project has it's own settings, then those validators are - * returned via this method. - * </p> - * <p> - * The following approach is used. For version 1 validators, the validator - * is only returned if it is defined to operate on this project type. This - * is the way that the previous version of the framework did it. For version - * 2 validators, they are all returned. - * </p> - * - * @param project - * this may be null, in which case the global preferences are - * returned. - * @param respectOverrideSettings - * if this is true then the validators that get returned are - * based on the override settings. So for example, if the global - * preferences do not allow project overrides then none of the - * project settings are used. Normal validation would set this to true. - * The properties page would set this to false. - * - * @deprecated Use {@link #getValidatorsNotCached(IProject)} instead - */ - public Validator[] getValidators(IProject project, boolean respectOverrideSettings) throws ProjectUnavailableError { - return getValidators(project); - } - - /** - * Answer a cached copy of the the validators for a given project. This is a front end method, - * for the getValidatorsNotCached() method. - * <p> - * Individual projects may override the global validation preference - * settings. If the project has it's own settings, then those validators are - * returned via this method. - * </p> - * <p> - * The following approach is used. For version 1 validators, the validator - * is only returned if it is defined to operate on this project type. This - * is the way that the previous version of the framework did it. For version - * 2 validators, they are all returned. - * </p> - * - * @param project - * This may be null, in which case the global preferences are - * returned. - * - * @return The validators in name sorted order. - */ - public Validator[] getValidators(IProject project) throws ProjectUnavailableError { - return _cache.getValidatorsCached(project); - } - - /** - * Answer all the validators for the given project. - * <p> - * Individual projects may override the global validation preference - * settings. If the project has it's own settings, then those validators are - * returned via this method. - * </p> - * <p> - * The following approach is used. For version 1 validators, the validator - * is only returned if it is defined to operate on this project type. This - * is the way that the previous version of the framework did it. For version - * 2 validators, they are all returned. - * </p> - * - * @param project - * This may be null, in which case the global preferences are - * returned. - * - * @return The validators in name sorted order. - */ - private Validator[] getValidatorsNotCached(IProject project) throws ProjectUnavailableError { - Map<String,Validator> v2Vals = getV2Validators(project, UseProjectPreferences.Normal); - TreeSet<Validator> sorted = new TreeSet<Validator>(); - sorted.addAll(v2Vals.values()); - - try { - ValidationConfiguration vc = ConfigurationManager.getManager().getConfiguration(project); - if (project == null){ - // If the project is null we need to use this approach, since you can not use new ManualValidatorsOperation(null) - ValidatorMetaData[] vmds = vc.getValidators(); - for (ValidatorMetaData vmd : vmds){ - Validator v = Validator.create(vmd, vc, project); - sorted.add(v); - } - } - else { - ManualValidatorsOperation mvo = new ManualValidatorsOperation(project); - Set<ValidatorMetaData> vmds = mvo.getEnabledValidators(); - for (ValidatorMetaData vmd : vmds){ - Validator v = Validator.create(vmd, vc, project); - sorted.add(v); - } - } - } - catch (InvocationTargetException e){ - ValidationPlugin.getPlugin().handleException(e); - } - - Validator[] vals = new Validator[sorted.size()]; - sorted.toArray(vals); - return vals; - } - /** - * Validators can use project level settings (Project natures and facets) to - * determine if they are applicable to the project or not. - * - * @param project - * The project that the configuration is based on. - * @param mustUseProjectSettings - * Force the project properties to be used. There is a case where the user has toggled the - * Enable project specific settings checkbox in the dialog, but has not yet committed the - * changes. This allows that setting to be passed through. - * @return The validators that are configured to run on this project based - * on the project level settings. These are the "live" validators, they are not copies. - * @throws ProjectUnavailableError - * - * @deprecated Use getValidatorsConfiguredForProject(IProject project, UseProjectPreferences useProject) - */ - public Validator[] getValidatorsConfiguredForProject(IProject project, boolean mustUseProjectSettings) throws ProjectUnavailableError { - UseProjectPreferences useProject = UseProjectPreferences.Normal; - return getValidatorsConfiguredForProject(project, useProject); - } - - /** - * Validators can use project level settings (Project natures and facets) to - * determine if they are applicable to the project or not. - * - * @param project - * The project that the configuration is based on. - * @param useProject - * Specifies how to use the project preferences. This can be used - * to force the project properties to be used. There is a case - * where the user has toggled the Enable project specific - * settings checkbox in the dialog, but has not yet committed the - * changes. This allows that setting to be passed through. - * @return The validators that are configured to run on this project based - * on the project level settings. These are the "live" validators, - * they are not copies. - * @throws ProjectUnavailableError - */ - public Validator[] getValidatorsConfiguredForProject(IProject project, UseProjectPreferences useProject) throws ProjectUnavailableError { - Map<String,Validator> v2Vals = getV2Validators(project, useProject); - TreeSet<Validator> sorted = new TreeSet<Validator>(); - sorted.addAll(v2Vals.values()); - - if (useProject == UseProjectPreferences.MustNotUse){ - sorted.addAll(ExtensionValidators.instance().getV1Validators(project)); - } - else { - try { - ValidationConfiguration vc = ConfigurationManager.getManager().getProjectConfiguration(project); - ValidatorMetaData[] vmds = vc.getValidators(); - for (ValidatorMetaData vmd : vmds) { - Validator v = Validator.create(vmd, vc, project); - sorted.add(v); - } - } - catch (InvocationTargetException e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - - List<Validator> list = new LinkedList<Validator>(); - for (Validator v : sorted){ - if (v.shouldValidateProject(project, false, false))list.add(v); - } - - Validator[]vals = new Validator[list.size()]; - list.toArray(vals); - return vals; - } - - /** - * Answer the V2 validators that are in effect for this project. The - * following approach is used: - * <ol> - * <li>The validators that are defined by the extension point are loaded.</li> - * <li>They are customized by any global preferences.</li> - * <li>If project customizations are allowed, they are customized by the - * project preferences. - * </ol> - * - * @param project - * This may be null, in which case only the global preferences - * are used. - * @param useProject - * Specifies how to use the project preferences. This can be used - * to force the project properties to be used. There is a case - * where the user has toggled the Enable project specific - * settings checkbox in the dialog, but has not yet committed the - * changes. This allows that setting to be passed through. - * - * @return - */ - private Map<String,Validator> getV2Validators(IProject project, UseProjectPreferences useProject){ - Map<String,Validator> extVals = ExtensionValidators.instance().getMapV2Copy(); - try { - List<Validator> vals = ValPrefManagerGlobal.getDefault().getValidators(); - for (Validator v : vals)extVals.put(v.getId(), v); - - if (useProject != UseProjectPreferences.MustNotUse){ - if (useProject == UseProjectPreferences.MustUse || !mustUseGlobalValidators(project)){ - //TODO should probably cache this vpm - ValPrefManagerProject vpm = new ValPrefManagerProject(project); - vals = vpm.getValidators(extVals); - for (Validator v : vals)extVals.put(v.getId(), v); - - for (Validator v : getProjectPreferences(project).getValidators())extVals.put(v.getId(), v); - } - } - } - catch (BackingStoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - return extVals; - } - - - /** - * Answer true if we must use the global settings for this project. If the global preferences do not - * allow overrides, or if this project does not allow overrides then the global preferences must be used. - * - * @param project project that is being tested. It can be null, in which case the global preferences must be used. - * @return true if the global preferences must be used. - */ - public boolean mustUseGlobalValidators(IProject project){ - if (project == null)return true; - if (!getGlobalPreferences().getOverride())return true; - ProjectPreferences pp = _projectPreferences.get(project); - if (pp != null)return !pp.getOverride(); - - ValPrefManagerProject vpm = new ValPrefManagerProject(project); - return !vpm.getOverride(); - } - - /** - * Answer the validator with the given id that is in effect for the given project. - * - * @param id The validator id. - * @param project - * @return null if the validator is not found - */ - public Validator getValidator(String id, IProject project){ - Validator[] vals = getValidators(project); - for (Validator v : vals){ - if (v.getId().equals(id))return v; - } - return null; - } - - /** - * @see ValidationFramework#getValidator(String, IProject) - */ - public Validator getValidatorWithId(String id, IProject project){ - Validator[] vals = getValidators(project); - for (Validator v : vals){ - if (v.getId().equals(id))return v; - } - return null; - } - - /** - * Answer true if the resource has any enabled validators. - * - * @param resource a file, folder or project. - * - * @param isManual if true then the validator must be turned on for manual validation. - * If false then the isManualValidation setting isn't used to filter out validators. - * - * @param isBuild if true then the validator must be turned on for build based validation. - * If false then the isBuildValidation setting isn't used to filter out validators. - */ - public boolean hasValidators(IResource resource, boolean isManual, boolean isBuild){ - if (resource instanceof IProject){ - IProject project = (IProject)resource; - return ValManager.getDefault().getValidators(project).length > 0; - } - else if (resource instanceof IFolder){ - IFolder folder = (IFolder)resource; - HasValidatorVisitor v = new HasValidatorVisitor(isManual, isBuild); - return v.hasValidator(folder); - } - else { - ContentTypeWrapper ctw = new ContentTypeWrapper(); - for (Validator val : ValManager.getDefault().getValidators(resource.getProject())){ - if (Friend.shouldValidate(val, resource, isManual, isBuild, ctw))return true; - } - } - return false; - } - - /** - * Answer true if the project has disabled all of it's validators, or if project overrides are not - * allowed if global validation has been disabled. - * - * @param project the project that is being consulted, or null if only the global settings are to be - * checked. - */ - public boolean isDisabled(IProject project){ - GlobalPreferences gp = getGlobalPreferences(); - if (!gp.getOverride() || project == null)return gp.getDisableAllValidation(); - - ProjectPreferences pp = _projectPreferences.get(project); - if (pp == null)return gp.getDisableAllValidation(); - return pp.getSuspend(); - } - - /** - * Answer all the registered validators as they were defined by the extension points. That is - * answer the validators as if the user has never applied any customizations. - * - * @return Answer an empty array if there are no validators. - */ - public static Validator[] getDefaultValidators() throws InvocationTargetException { - Map<String,Validator> extVals = ExtensionValidators.instance().getMapV2(); - TreeSet<Validator> sorted = new TreeSet<Validator>(); - for (Validator v : extVals.values())sorted.add(v); - - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - GlobalConfiguration gc = new GlobalConfiguration(root); - gc.resetToDefault(); - for (ValidatorMetaData vmd : gc.getValidators()){ - Validator v = Validator.create(vmd, gc, null); - v.setBuildValidation(vmd.isBuildValidation()); - v.setManualValidation(vmd.isManualValidation()); - sorted.add(v); - } - - Validator[] val = new Validator[sorted.size()]; - sorted.toArray(val); - return val; - } - - public static Validator[] getDefaultValidators(IProject project) throws InvocationTargetException { - Map<String,Validator> extVals = ExtensionValidators.instance().getMap(project); - Validator[] val = new Validator[extVals.size()]; - extVals.values().toArray(val); - return val; - } - - /** - * Answer all the registered validators. - * - * @param project the project to use for getting the version 1 validator settings. This can - * be null in which case the global preferences are used. - * - * @return Answer an empty array if there are no validators. - */ -// Validator[] getValidators2(IProject project) throws ProjectUnavailableError { -// // If I use a local variable I don't need to synchronize the method. -// -// Validator[] validators = _validators; -// if (project == null && validators != null)return validators; -// -// Validator[] val = loadExtensions(false, project); -// ValPrefManagerGlobal vpm = ValPrefManagerGlobal.getDefault(); -// if (!vpm.loadPreferences(val)){ -// val = restoreDefaults2(project); -// saveStateTimestamp(); -// } -// else { -// if (getGlobalPreferences().getStateTimeStamp() != Platform.getStateStamp()) -// val = migrateSettings(val, project); -// } -// -// TreeSet<Validator> set = new TreeSet<Validator>(); -// for (Validator v : val)set.add(v); -// -// List<Validator> list = new LinkedList<Validator>(); -// try { -// ValidationConfiguration vc = ConfigurationManager.getManager().getConfiguration(project); -// for (ValidatorMetaData vmd : vc.getValidators()){ -// list.add(Validator.create(vmd, vc, project)); -// } -// -// } -// catch (InvocationTargetException e){ -// if (project != null && (!project.exists() || !project.isOpen())) -// throw new ProjectUnavailableError(project); -// ValidationPlugin.getPlugin().handleException(e); -// } -// -// set.addAll(list); -// val = new Validator[set.size()]; -// set.toArray(val); -// if (project == null)_validators = val; -// return val; -// } - - /** - * This method needs to be called whenever the validation configuration has changed. - */ - private void configHasChanged(){ - _configNumber.incrementAndGet(); - ValidatorProjectManager.reset(); - _cache.reset(); - } - - /** - * Answer the global validation preferences. - */ - public GlobalPreferences getGlobalPreferences(){ - GlobalPreferences gp = _globalPreferences.get(); - if (gp == null){ - ValPrefManagerGlobal vpm = ValPrefManagerGlobal.getDefault(); - gp = vpm.loadGlobalPreferences(); - if (!_globalPreferences.compareAndSet(null, gp))gp = _globalPreferences.get(); - } - return gp; - } - - /** - * Update the global preferences, but only if something has actually changed. - * @param values The global settings. - * @return a bit mask of the changes between the old values and the new values. See the GlobalPreferences - * constants for the bit mask values. If a zero is return there were no changes. - */ - public int replace(GlobalPreferencesValues values){ - GlobalPreferences gp = new GlobalPreferences(values); - GlobalPreferences old = getGlobalPreferences(); - int changes = old.compare(gp); - if (changes != 0){ - _globalPreferences.set(gp); - } - return changes; - } - - /** - * Answer the project preferences for this project. - * @param project The project, this may be null. - */ - public ProjectPreferences getProjectPreferences(IProject project) { - ProjectPreferences pp = _projectPreferences.get(project); - if (pp != null)return pp; - - /* hopefully we rarely get this far */ - - Map<String,Validator> extVals = ExtensionValidators.instance().getMapV2Copy(); - try { - List<Validator> vals = ValPrefManagerGlobal.getDefault().getValidators(); - for (Validator v : vals)extVals.put(v.getId(), v); - - pp = getProjectPreferences(project, extVals); - } - catch (BackingStoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - return pp; - } - - /** - * - * @param project The project, this may be null. - * @param baseValidators - */ - private ProjectPreferences getProjectPreferences(IProject project, Map<String, Validator> baseValidators) - throws BackingStoreException { - ProjectPreferences pp = _projectPreferences.get(project); - if (pp != null)return pp; - - ValPrefManagerProject vpm = new ValPrefManagerProject(project); - pp = vpm.loadProjectPreferences(project, baseValidators); - _projectPreferences.put(project, pp); - return pp; - } - - /** - * Restore all the validation defaults, as defined by the individual validators via the - * validation extension point. - */ -// public synchronized void restoreDefaults() { -// getGlobalPreferences().resetToDefault(); -// _validators = null; -// getValidators(true); -// } - - - /** - * Run all the validators that are applicable to this resource. - * <p> - * If this is a manual validation both the version 1 and version 2 validators are run. If it - * is a build validation, then only the version 2 validators are run, because the old framework handles - * the running of the old validators. - * </p> - * - * @param project project that is being validated - * - * @param resource the resource that is being validated - * - * @param kind the kind of resource delta. It will be one of the IResourceDelta constants, like - * IResourceDelta.CHANGED for example. - * - * @param valType The type of validation request. - * @param buildKind the kind of build that triggered this validation. See IncrementalProjectBuilder for values. - * @param operation the operation that this validation is running under - * @param monitor the monitor to use to report progress - */ - public void validate(IProject project, final IResource resource, final int kind, ValType valType, - int buildKind, ValOperation operation, final IProgressMonitor monitor) { - - MarkerManager.getDefault().deleteMarkers(resource, operation.getStarted(), IResource.DEPTH_ZERO); - - IValidatorVisitor visitor = new IValidatorVisitor(){ - - public void visit(Validator validator, IProject project, ValType vt, - ValOperation operation, IProgressMonitor monitor) { - - Validator.V1 v1 = validator.asV1Validator(); - if (vt == ValType.Build && v1 != null)return; - - SubMonitor subMonitor = SubMonitor.convert(monitor); - String task = NLS.bind(ValMessages.LogValStart, validator.getName(), resource.getName()); - subMonitor.beginTask(task, 1); - validate(validator, operation, resource, kind, subMonitor.newChild(1), null); - } - }; - SubMonitor sm = SubMonitor.convert(monitor, getValidators(project).length); - accept(visitor, project, resource, valType, operation, sm); - - } - - /** - * Validate a single resource with a single validator. This will call the validator whether the validator - * is enabled or not. - * <p> - * Callers of this method should ensure that the shouldValidate was tested before making this call. - * - * @param validator the validator - * @param operation the operation that the validation is running in. - * @param resource the resource to validate - * @param kind the kind of resource change. See IResourceDelta. - * @param monitor - */ - public void validate(Validator validator, ValOperation operation, IResource resource, int kind, - IProgressMonitor monitor, ValidationEvent event){ - if (operation.isValidated(validator.getId(), resource))return; - long time = 0; - long cpuTime = -1; - String msg1 = NLS.bind(ValMessages.LogValStart, validator.getName(), resource.getName()); - monitor.subTask(msg1); - IPerformanceMonitor pm = ValidationFramework.getDefault().getPerformanceMonitor(); - if (pm.isCollecting()){ - time = System.currentTimeMillis(); - cpuTime = Misc.getCPUTime(); - } - - if (Tracing.matchesExtraDetail(validator.getId())){ - Tracing.log("ValManager-03: validating ", resource); //$NON-NLS-1$ - } - ValidationResult vr = validator.validate(resource, kind, operation, monitor, event); - if (pm.isCollecting()){ - if (cpuTime != -1){ - cpuTime = Misc.getCPUTime() - cpuTime; - } - int num = 0; - if (vr != null)num = vr.getNumberOfValidatedResources(); - PerformanceCounters pc = new PerformanceCounters(validator.getId(), - validator.getName(), resource.getName(), - num, System.currentTimeMillis()-time, cpuTime); - pm.add(pc); - } - if (ValidationPlugin.getPlugin().isDebugging() && !pm.isCollecting()){ - String msg = time != 0 ? - NLS.bind(ValMessages.LogValEndTime, new Object[]{validator.getName(), - validator.getId(), resource, Misc.getTimeMS(System.currentTimeMillis()-time)}) : - NLS.bind(ValMessages.LogValEnd, validator.getName(), resource); - Tracing.log("ValManager-01: " + msg); //$NON-NLS-1$ - } - if (vr != null){ - operation.mergeResults(vr); - if (vr.getSuspendValidation() != null)operation.suspendValidation(vr.getSuspendValidation(), validator); - } - } - - /** - * Accept a visitor for all the validators that are enabled for the given project. - * - * @param visitor - * @param project - * @param valType the type of validation - * @param operation - * @param monitor - */ - public void accept(IValidatorVisitor visitor, IProject project, ValType valType, - ValOperation operation, IProgressMonitor monitor){ - - if (isDisabled(project))return; - - for (Validator val : getValidators(project)){ - if (monitor.isCanceled())return; - if (!ValidatorProjectManager.get().shouldValidate(val, project, valType))continue; - if (operation.isSuspended(val, project))continue; - try { - visitor.visit(val, project, valType, operation, monitor); - } - catch (Exception e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - } - - /** - * Accept a visitor for all the validators that are enabled for the given project, resource, - * and validation mode. - * - * @param valType the type of validation request - */ - public void accept(IValidatorVisitor visitor, IProject project, IResource resource, - ValType valType, ValOperation operation, IProgressMonitor monitor){ - - if (isDisabled(project))return; - - Map<String,IValidatorGroupListener[]> groupListeners = new HashMap<String,IValidatorGroupListener[]>(); - - ValProperty vp = getValProperty(resource, valType, _configNumber.get()); - if (vp != null){ - BitSet bs = vp.getConfigSet(); - for (Validator val : getValidators(project)){ - if (!monitor.isCanceled()) { - if (!bs.get(_idManager.getIndex(val.getId())))continue; - if (operation.isSuspended(val, project))continue; - Validator.V2 v2 = val.asV2Validator(); - if (v2 != null) { - notifyGroupListenersStarting(resource, operation.getState(), monitor, groupListeners, v2); - } - try { - visitor.visit(val, project, valType, operation, monitor); - } - catch (Exception e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - } - notifyGroupFinishing(resource, operation.getState(), monitor, groupListeners); - return; - } - - vp = new ValProperty(); - vp.setConfigNumber(_configNumber.get()); - ContentTypeWrapper ctw = new ContentTypeWrapper(); - for (Validator val : getValidators(project)){ - if (!monitor.isCanceled()) { - if (!ValidatorProjectManager.get().shouldValidate(val, project, valType))continue; - if (Friend.shouldValidate(val, resource, valType, ctw)){ - vp.getConfigSet().set(_idManager.getIndex(val.getId())); - // we do the suspend check after figuring out if it needs to be validated, because we save - // this information for the session. - if (operation.isSuspended(val, project))continue; - Validator.V2 v2 = val.asV2Validator(); - if (v2 != null) { - notifyGroupListenersStarting(resource, operation.getState(), monitor, groupListeners, v2); - } - try { - visitor.visit(val, project, valType, operation, monitor); - } - catch (Exception e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - } - } - notifyGroupFinishing(resource, operation.getState(), monitor, groupListeners); - putValProperty(vp, resource, valType); - } - - /** - * Let the group listeners know that validation might be starting for the group of validators. - */ - private void notifyGroupListenersStarting(final IResource resource, - final ValidationState state, final IProgressMonitor monitor, - Map<String, IValidatorGroupListener[]> groupListeners, Validator.V2 v2) { - - String[] groups = v2.getValidatorGroups(); - for (String group : groups) { - if (!groupListeners.containsKey(group)) { - IValidatorGroupListener[] createdListeners = null; - try { - createdListeners = ValidatorGroupExtensionReader.getDefault().createListeners(group); - } - catch (CoreException e){ - String msg = NLS.bind(ValMessages.ErrConfig, v2.getId()); - Status status = new Status(IStatus.ERROR, ValidationPlugin.PLUGIN_ID, msg); - CoreException core = new CoreException(status); - ValidationPlugin.getPlugin().handleException(core); - ValidationPlugin.getPlugin().handleException(e); - - // we create this to ensure that we don't signal the same exception over and over. - createdListeners = new IValidatorGroupListener[0]; - } - - // create and notify just this once - final IValidatorGroupListener[] listeners = createdListeners; - - groupListeners.put(group, listeners); - for (final IValidatorGroupListener listener : listeners) { - SafeRunner.run(new ISafeRunnable() { - public void run() throws Exception { - listener.validationStarting(resource, monitor, state); - } - - public void handleException(Throwable exception) { - ValidationPlugin.getPlugin().handleException(exception); - } - }); - } - } - } - } - - /** - * Let the group listeners know that validation is finished for the group of validators. - */ - private void notifyGroupFinishing(final IResource resource, - final ValidationState state, final IProgressMonitor monitor, - Map<String, IValidatorGroupListener[]> groupListeners) { - for (final IValidatorGroupListener[] listeners : groupListeners.values()) { - for (final IValidatorGroupListener listener : listeners) { - SafeRunner.run(new ISafeRunnable() { - public void run() throws Exception { - listener.validationFinishing(resource, monitor, state); - } - - public void handleException(Throwable exception) { - ValidationPlugin.getPlugin().handleException(exception); - } - }); - } - } - } - - private ValProperty getValProperty(IResource resource, ValType valType, int configNumber) { - ValProperty vp = null; - try { - if (valType == ValType.Build)vp = (ValProperty)resource.getSessionProperty(StatusBuild); - else if (valType == ValType.Manual)vp = (ValProperty)resource.getSessionProperty(StatusManual); - } - catch (CoreException e){ - // don't care about this one - } - if (vp == null)return null; - if (vp.getConfigNumber() != _configNumber.get())return null; - return vp; - } - - /** - * Let the validation manager know that a project has been changed. - * - * @param project The project that has been opened, created, or had it's description change. - */ - public void projectChanged(IProject project){ - ValidatorProjectManager.reset(); - _projectPreferences.remove(project); - _cache.reset(project); - } - - /** - * Let the validation manager know that a project has been removed. - * - * @param project The project that has been closed or deleted. - * - */ - public void projectRemoved(IProject project){ - ValidatorProjectManager.reset(); - _projectPreferences.remove(project); - _cache.reset(project); - } - - private void putValProperty(ValProperty vp, IResource resource, ValType valType) { - try { - if (valType == ValType.Build)resource.setSessionProperty(StatusBuild, vp); - else if (valType == ValType.Manual)resource.setSessionProperty(StatusManual, vp); - } - catch (CoreException e) { - // If the resource is not found, it is likely just been deleted - // and there is no need to do anything. - // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=269022 - if (!e.getStatus().equals(IResourceStatus.RESOURCE_NOT_FOUND)) { - ValidationPlugin.getPlugin().handleException(e, IStatus.WARNING); - } - } - } - - /** - * Let each of the enabled validators know that a clean has been requested. - * - * @param project the project that is being cleaned, or null if the entire workspace is being cleaned. - * @param monitor - */ - void clean(final IProject project, final ValOperation operation, final IProgressMonitor monitor) { - IValidatorVisitor visitor = new IValidatorVisitor(){ - - public void visit(Validator validator, IProject project, ValType valType, - ValOperation operation, IProgressMonitor monitor) { - validator.clean(project, operation, monitor); - } - - }; - accept(visitor, project, ValType.Build, operation, monitor); - } - - /** - * Let each of the enabled validators know that a clean has been requested. - * - * @param project the project that is being cleaned, or null if the entire workspace is being cleaned. - * @param monitor - */ - public void clean(IProject project, IProgressMonitor monitor){ - IValidatorVisitor visitor = new IValidatorVisitor(){ - - public void visit(Validator validator, IProject project, ValType valType, - ValOperation operation, IProgressMonitor monitor) { - validator.clean(project, operation, monitor); - } - - }; - ValidationFramework.getDefault().getDependencyIndex().clear(project); - ValOperation operation = new ValOperation(); - accept(visitor, project, ValType.Build, operation, monitor); - } - - public void validatorsForProjectChanged(IProject project, boolean validationSettingChanged) { - if (validationSettingChanged){ - if (project != null)_projectPreferences.remove(project); - configHasChanged(); - } - } - - private final class HasValidatorVisitor implements IResourceVisitor { - - private boolean _hasValidator; - private final boolean _isManual; - private final boolean _isBuild; - - public HasValidatorVisitor(boolean isManual, boolean isBuild){ - _isManual = isManual; - _isBuild = isBuild; - } - - public boolean hasValidator(IFolder folder){ - try { - folder.accept(this); - } - catch (CoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - return _hasValidator; - } - - public boolean visit(IResource resource) throws CoreException { - if (resource instanceof IFolder)return true; - if (hasValidators(resource, _isManual, _isBuild)){ - _hasValidator = true; - return false; - } - return true; - } - } - - /** - * Map validator id's to an index number on a bit set, so that we can quickly determine if a - * particular validator needs to validate a particular resource. - * @author karasiuk - * - */ - private final static class ValidatorIdManager { - - /** - * Map validator id's to Integers. The integers correspond to bits in the ValProperty instances. - */ - private final Map<String, Integer> _map = new HashMap<String, Integer>(100); - private final Map<Integer, String> _reverseMap = new HashMap<Integer, String>(100); - - /** Next available bit. */ - private int _next; - - /** - * Answer the index number for this validator. If we haven't seen it yet allocate a new index number. - * @param id validator id. - * @return index into the validator bit mask. - */ - public synchronized int getIndex(String id){ - Integer i = _map.get(id); - if (i != null)return i; - - i = _next++; - _map.put(id, i); - _reverseMap.put(i, id); - - return i; - } - - /** - * Answer the validator id for the index. - * @param index - * @return null if the index number has not been set. - */ - public synchronized String getId(Integer index){ - return _reverseMap.get(index); - } - - public synchronized void reset(){ - _map.clear(); - _reverseMap.clear(); - _next = 0; - } - - /** - * Answer the ids for the bit in the bitset. This is used for debugging. - * @param bs - */ - public synchronized String[] getIds(BitSet bs){ - List<String> list = new LinkedList<String>(); - for(int i=bs.nextSetBit(0); i>=0; i=bs.nextSetBit(i+1)) { - String id = getId(i); - if (id != null)list.add(id); - } - String[] s = new String[list.size()]; - return list.toArray(s); - } - } - - /** - * This is used to keep track of which validators are enabled with which projects. We want to ensure - * that we don't activate a validator (and it's plug-in) if it has nothing to validate in the workspace. - * This is an immutable object. - * @author karasiuk - * - */ - private final static class ValidatorProjectManager { - - private final static AtomicReference<ValidatorProjectManager> _me = new AtomicReference<ValidatorProjectManager>(); - private final static AtomicInteger _counter = new AtomicInteger(); - - private final ValProjectMap _manual = new ValProjectMap(ValType.Manual); - private final ValProjectMap _build = new ValProjectMap(ValType.Build); - private final int _sequence; - - /** - * Answer the most current ValidatorProjectManager creating a new one if you have to. - * @return - */ - public static ValidatorProjectManager get(){ - ValidatorProjectManager vpm = _me.get(); - if (vpm != null)return vpm; - - int next = _counter.incrementAndGet(); - ValidatorProjectManager newVpm = null; - boolean looking = true; - while(looking){ - vpm = _me.get(); - if (vpm == null || next > vpm.getSequence()){ - if (newVpm == null)newVpm = new ValidatorProjectManager(next); - if (_me.compareAndSet(vpm, newVpm))return newVpm; - } - else looking = false; - } - return vpm; - } - - /** - * Reset the ValidatorProjectManager to null, which will force a newer one to be created the next time - * that it is requested. - */ - public static void reset(){ - int next = _counter.incrementAndGet(); - ValidatorProjectManager vpm = _me.get(); - if ( vpm == null)return; - if (next > vpm.getSequence())_me.compareAndSet(vpm, null); - } - - private ValidatorProjectManager(int sequence){ - _sequence = sequence; - } - - int getSequence(){ - return _sequence; - } - - /** - * Should this validator attempt to validate any resources in this project? - * - * @param validator - * The validator that is being tested. - * @param project - * The project that is being tested. This can be null, which - * means that all projects will be tested. - * @param type - * The type of validation operation. - * @return true if the validator should attempt to validate. - */ - public boolean shouldValidate(Validator validator, IProject project, ValType type){ - if (type == ValType.Build)return _build.shouldValidate(validator, project); - if (type == ValType.Manual)return _manual.shouldValidate(validator, project); - - return false; - } - - /** - * This is used to keep track of which validators are enabled for which projects. We want to ensure - * that we don't activate a validator (and it's plug-in) if it has nothing to validate in the workspace. - * <p> - * There are two reasons why a validator may not be enabled. It's current project level filters may not match - * the project. Or the entire validator may have been turned off for the project. - * </p> - * @author karasiuk - * - */ - private final static class ValProjectMap { - /** - * Map a validator to the projects that it validates. This is an immutable object. - * <p> - * I've gone back and forth on whether the key should - * be a Validator or the validator id. I'm back to it being the id because I was - * running into cases where because of copying I wasn't getting the matches that I expected and I - * want to ensure that I don't leak validators. If I run into - * false matches, it is probably because reset isn't being called when it should be. - * </p> - */ - private final Map<String, Set<IProject>> _map; - - private final ValType _type; - - public ValProjectMap(ValType type){ - _type = type; - _map = load(); - } - - /** - * Should this validator attempt to validate any resources in this project? - * - * @param validator - * The validator that is being tested. - * @param project - * The project that is being tested. This can be null, which - * means that all projects will be tested, and if any of them return true, - * then true is answered for this method. - * - * @return true if the validator should attempt to validate. - */ - public boolean shouldValidate(Validator validator, IProject project){ - String vid = validator.getId(); - Set<IProject> projects = _map.get(vid); - if (projects == null)return false; - if (project == null)return projects.size() > 0; - return projects.contains(project); - } - - /** - * For each of the projects in the workspace, load which validators are currently prepared to validate things. - */ - private Map<String, Set<IProject>> load() { - Map<String, Set<IProject>> map = new HashMap<String, Set<IProject>>(50); - ValManager vm = ValManager.getDefault(); - IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); - Tracing.log("ValManager-02: loading " + projects.length + " projects"); //$NON-NLS-1$//$NON-NLS-2$ - for (IProject project : projects){ - if (!project.isOpen())continue; - Validator[] vals = vm.getValidators(project); - for (Validator v : vals){ - String vid = v.getId(); - Set<IProject> set = map.get(vid); - if (set == null){ - set = new HashSet<IProject>(50); - map.put(vid, set); - } - - if (v.shouldValidateProject(project, _type))set.add(project); - } - } - return map; - } - - } - - } - - public void handleEvent(IFacetedProjectEvent event) { - projectChanged(event.getProject().getProject()); - } - - public void projectChanged(IProject project, int type) { - switch (type){ - case IProjectChangeListener.ProjectClosed: - case IProjectChangeListener.ProjectDeleted: - projectRemoved(project); - break; - case IProjectChangeListener.ProjectOpened: - case IProjectChangeListener.ProjectChanged: - case IProjectChangeListener.ProjectAdded: - projectChanged(project); - break; - } - } - - /** - * Store the singleton for the ValManager. This approach is used to avoid having to synchronize the - * ValManager.getDefault() method. - * - * @author karasiuk - * - */ - private static class Singleton { - static ValManager valManager = new ValManager(); - } - - private final class ValidatorCache { - private final ConcurrentMap<IProject, Validator[]> _cache = new ConcurrentHashMap<IProject, Validator[]>(50); - private final AtomicReference<Validator[]> _global = new AtomicReference<Validator[]>(); - - public Validator[] getValidatorsCached(IProject project) throws ProjectUnavailableError { - Validator[] vals = null; - if (project == null){ - vals = _global.get(); - if (vals == null){ - vals = getValidatorsNotCached(project); - _global.set(vals); - } - } - else { - vals = _cache.get(project); - if (vals == null){ - vals = getValidatorsNotCached(project); - _cache.put(project, vals); - } - } - return vals; - } - - public void reset(){ - _cache.clear(); - _global.set(null); - } - - public void reset(IProject project){ - if (project != null)_cache.remove(project); - } - - } - - public enum UseProjectPreferences {Normal, MustUse, MustNotUse} - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValMessages.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValMessages.java deleted file mode 100644 index 84ac62a38..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValMessages.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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.wst.validation.internal; - -import org.eclipse.osgi.util.NLS; - -public class ValMessages extends NLS { - - private static final String BUNDLE_NAME = "org.eclipse.wst.validation.internal.messages"; //$NON-NLS-1$ - - public static String ConfigError; - - public static String DecodeError1; - public static String Error20; - public static String Error21; - - public static String ErrConfig; - public static String ErrFilterRule; - public static String ErrGroupName; - public static String ErrDependencyVersion; - - public static String ErrGroupNoType; - public static String ErrGroupInvalidType; - - public static String ErrPatternAttrib; - public static String ErrTypeReq; - public static String ErrType; - - public static String VbfExcSyntaxNoValClass; - public static String VbfExcSyntaxNoValRun; - public static String VbfExcSyntaxNoValNull; - - public static String GroupInclude; - - public static String GroupExclude; - - public static String JobName; - public static String JobNameMonitor; - - public static String JobIndexSave; - - public static String LogValStart; - public static String LogValEnd; - public static String LogValEndTime; - public static String LogValSummary; - public static String LogValSummary2; - public static String LogSession; - - public static String MigrationJobName; - - public static String RogueValidator; - - public static String RuleProjectNature; - public static String RuleFileExt; - public static String RuleFile; - public static String RuleFolder; - public static String RuleFull; - public static String RuleContentType; - public static String RuleFacet; - public static String RulePattern; - - public static String ContentTypeExact; - public static String ContentTypeNotExact; - - public static String FileExtWithCase; - public static String FileExtWithoutCase; - - public static String SevError; - public static String SevWarning; - public static String SevIgnore; - - public static String TimeUnder; - public static String TimeNano; - public static String TimeMicro; - public static String TimeSec; - public static String TimeMin; - - public static String TypeInclude; - public static String TypeExclude; - - static { - NLS.initializeMessages(BUNDLE_NAME, ValMessages.class); - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValOperation.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValOperation.java deleted file mode 100644 index 44c78ecd6..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValOperation.java +++ /dev/null @@ -1,205 +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.wst.validation.internal; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.wst.validation.ValidationResult; -import org.eclipse.wst.validation.ValidationResults; -import org.eclipse.wst.validation.ValidationState; -import org.eclipse.wst.validation.Validator; - -/** - * This represents a validation operation, i.e. the running of a set of validators in response to some change. - * It may be a large operation, as would happen on a clean build, or it may be the validation of just a single - * resource. - * <p> - * The operation can, but doesn't need to, span multiple projects. - * </p> - * <p> - * Once the operation has finished, this object goes away. - * </p> - * @author karasiuk - * - */ -public final class ValOperation { - - private final ValidationState _state = new ValidationState(); - private final ValidationResult _result = new ValidationResult(); - - /** - * Each project can have a set of validators that are suspended for the duration of the validation operation. - * The set contains the validator's id. - */ - private final Map<IProject, Set<String>> _suspended = new HashMap<IProject, Set<String>>(40); - - /** The time that the operation started. */ - private final long _started = System.currentTimeMillis(); - - /** - * Are we in a multi project validation? That is, could we be validating several - * projects at the same time? This can be triggered by either clean all or - * if auto build is turned off, a build all. - */ - private final boolean _multiProject; - - /** - * Holds all the resources that have been validated as a side-effect of running other validations. - * The key is the validator id and the value is a Set of IResources. - */ - private final Map<String, Set<IResource>> _validated = new HashMap<String, Set<IResource>>(20); - - public ValOperation(){ - _multiProject = false; - } - - /** - * - * @param multiProject Set to true if we could be validating several projects at the same time. - */ - public ValOperation(boolean multiProject){ - _multiProject = multiProject; - } - - public ValidationState getState() { - return _state; - } - - /** - * Answer a summary of the validation results. - * @return - */ - public ValidationResultSummary getResult() { - synchronized(_result){ - ValidationResultSummary vrs = new ValidationResultSummary(_result.getSeverityError(), - _result.getSeverityWarning(), _result.getSeverityInfo()); - return vrs; - } - } - - /** - * Answer a copy of the ValidationResult. - * @return - */ - public ValidationResults getResults(){ - return new ValidationResults(_result); - } - - /** - * Remember that this resource has already been validated as a side-effect. - * - * @param id id of the validator - * @param resource resource that has been validated. - */ - public void addValidated(String id, IResource resource){ - synchronized(_validated){ - Set<IResource> set = _validated.get(id); - if (set == null){ - set = new HashSet<IResource>(20); - _validated.put(id, set); - } - set.add(resource); - } - } - - /** - * Answer if this resource has already been validated as a side-effect of some other validation by the - * given validator. - * - * @param id - * @param resource - */ - public boolean isValidated(String id, IResource resource){ - synchronized(_validated){ - Set<IResource> set = _validated.get(id); - if (set == null)return false; - - return set.contains(resource); - } - } - - /** - * Has this validator been suspended for the duration of this operation on this project? - * - * @param val - * The validator that is being checked. - * @param project - * Can be null, in which case we return false. - * - * @return true if this validator should not run on this project. - */ - public boolean isSuspended(Validator val, IProject project) { - if (project == null)return false; - synchronized(_suspended){ - Set<String> set = getSuspended(project); - return set.contains(val.getId()); - } - } - - private Set<String> getSuspended(IProject project){ - Set<String> set = _suspended.get(project); - if (set == null){ - set = new HashSet<String>(5); - _suspended.put(project, set); - } - return set; - } - - void suspendValidation(IProject project, Validator validator) { - if (project == null)return; - if (validator == null)return; - getSuspended(project).add(validator.getId()); - } - - public long getStarted() { - return _started; - } - - public boolean isMultiProject() { - return _multiProject; - } - - /** - * Indicate if the operation was canceled. - * - * @param canceled - * Set to true if it was canceled and false if it was not canceled. - */ - public void setCanceled(boolean canceled) { - synchronized (_result) { - _result.setCanceled(canceled); - } - - } - - /** - * Was the operation canceled before it completed? For example if the validation is being run through the - * user interface, the end user can cancel the operation through the progress monitor. - * - * @return true if the operation was canceled - */ - public boolean isCanceled() { - synchronized (_result) { - return _result.isCanceled(); - } - } - - public void mergeResults(ValidationResult vr) { - synchronized (_result) { - _result.mergeResults(vr); - } - } -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerGlobal.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerGlobal.java deleted file mode 100644 index 5fcbaf342..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerGlobal.java +++ /dev/null @@ -1,653 +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.wst.validation.internal; - -import java.lang.reflect.InvocationTargetException; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.atomic.AtomicReference; - -import org.eclipse.wst.validation.Friend; -import org.eclipse.wst.validation.MessageSeveritySetting; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.Validator.V2; -import org.eclipse.wst.validation.internal.model.FilterGroup; -import org.eclipse.wst.validation.internal.model.GlobalPreferences; -import org.eclipse.wst.validation.internal.model.GlobalPreferencesValues; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; -import org.osgi.service.prefs.BackingStoreException; - -/** - * A class that knows how to manage the global persisted validation settings. - * @author karasiuk - */ -public final class ValPrefManagerGlobal { - - /** - * Version of the framework properties. - * <ul> - * <li>Version 2 - used the filter approach - * <li>Version 3 - switched to a difference based approach. (See Bugzilla 224179) - * </ul> - * - */ - public final static int frameworkVersion = 3; - - private final Set<IValChangedListener> _listeners = new CopyOnWriteArraySet<IValChangedListener>(); - - private final AtomicReference<List<Validator>> _validators = new AtomicReference<List<Validator>>(); - - private ValPrefManagerGlobal(){} - - public static ValPrefManagerGlobal getDefault(){ - return Singleton.valPrefManagerGlobal; - } - - public void addListener(IValChangedListener listener){ - _listeners.add(listener); - } - - public void removeListener(IValChangedListener listener){ - _listeners.remove(listener); - } - - private void updateListeners(boolean validationSettingChanged){ - for (IValChangedListener cl : _listeners)cl.validatorsForProjectChanged(null, validationSettingChanged); - } - - /** - * Update the validator filters from the preference store. - * - * @param val - * - * @return false if there are no preferences, that means that the user has never changed any - * of the default settings. Also answer false if there was some sort of error, which essentially - * means that the preferences aren't valid for whatever reason. - * - * @deprecated - */ -// public boolean loadPreferences(Validator[] val) { -// -// try { -// IEclipsePreferences pref = ValidationFramework.getDefault().getPreferenceStore(); -// if (!pref.nodeExists(PrefConstants.filters))return false; -// -// Preferences filters = pref.node(PrefConstants.filters); -// for (Validator v : val){ -// String id = v.getId(); -// if (filters.nodeExists(id)){ -// Preferences vp = filters.node(id); -// loadPreferences(v, vp); -// } -// } -// } -// catch (Exception e){ -// ValidationPlugin.getPlugin().handleException(e); -// return false; -// } -// -// return true; -// } - - /** - * Answer the v2 validators that have been overridden by the global preferences. - */ - public List<Validator> getValidators() throws BackingStoreException { - List<Validator> vals = _validators.get(); - while (vals == null){ - vals = loadValidators(); - if (!_validators.compareAndSet(null, vals))vals = _validators.get(); - } - return vals; - } - - /** - * Load the validators from the preference store. - * @return the validators that have been overridden by the global references. - */ - private List<Validator> loadValidators() throws BackingStoreException { - LinkedList<Validator> list = new LinkedList<Validator>(); - PreferencesWrapper pref = PreferencesWrapper.getPreferences(null, null); - if (pref.nodeExists(PrefConstants.vals)){ - PreferencesWrapper vals = pref.node(PrefConstants.vals); - for (String id : vals.childrenNames()){ - Validator base = ExtensionValidators.instance().getMapV2().get(id); - Validator v = loadValidator(id, vals, base); - if (v != null){ - V2 v2 = v.asV2Validator(); - if (v2 != null)v2.setLevel(Validator.Level.Global); - list.add(v); - } - } - } - return list; - } - - /** - * Answer a copy of the validator that has been updated with the given preferences. - * - * @param id - * Validator id. - * @param valsNode - * The /vals node in the preference store. - * @param base - * The base validator that is being customized. This can be null, - * in which case null will be returned. - * - * @return A new validator that is a copy of the extension point validator - * with the updates from the preference store. - */ - static Validator loadValidator(String id, PreferencesWrapper valsNode, Validator base) { - if (base == null)return null; - - PreferencesWrapper vp = valsNode.node(id); - base = base.copy(); - V2 v2 = base.asV2Validator(); - - String global = vp.get(PrefConstants.global, ""); //$NON-NLS-1$ - if (global.length() > 0){ - Global g = new Global(global); - base.setBuildValidation(g.isBuild()); - base.setManualValidation(g.isManual()); - base.setDelegatingId(g.getDelegating()); - } - - if (v2 != null){ - String groups = vp.get(PrefConstants.groups, ""); //$NON-NLS-1$ - if (groups.length() > 0){ - List<FilterGroup> list = new LinkedList<FilterGroup>(); - Deserializer des = new Deserializer(groups); - while(des.hasNext())list.add(FilterGroup.create(des)); - v2.setGroups(list); - } - } - return base; - } - - /** - * The only valid way to get the global preferences is through the ValManager. - * - * @see ValManager#getGlobalPreferences() - */ - public GlobalPreferences loadGlobalPreferences() { - PreferencesWrapper pref = PreferencesWrapper.getPreferences(null, null); - GlobalPreferencesValues gp = new GlobalPreferencesValues(); - gp.saveAutomatically = pref.getBoolean(PrefConstants.saveAuto, GlobalPreferences.DefaultAutoSave); - gp.disableAllValidation = pref.getBoolean(PrefConstants.suspend, GlobalPreferences.DefaultSuspend); - gp.confirmDialog = pref.getBoolean(PrefConstants.confirmDialog, GlobalPreferences.DefaultConfirm); - gp.override = pref.getBoolean(PrefConstants.override, GlobalPreferences.DefaultOverride); - gp.version = pref.getInt(PrefConstants.frameworkVersion, GlobalPreferences.DefaultFrameworkVersion); - gp.stateTimeStamp = pref.getLong(PrefConstants.stateTS, 0); - - if (gp.version != frameworkVersion)migrate(gp.version, pref); - return new GlobalPreferences(gp); - } - - /** - * If necessary migrate the preferences. - * @param version The incoming version of the preferences. - * @param pref the root of the preference store - */ - static void migrate(int version, PreferencesWrapper pref) { - try { - boolean update = false; - if (version == 2){ - if (pref.nodeExists(PrefConstants.filters)){ - pref.node(PrefConstants.filters).removeNode(); - update = true; - } - if (pref.nodeExists(PrefConstants.msgs)){ - pref.node(PrefConstants.msgs).removeNode(); - update = true; - } - } - if (update){ - pref.putInt(PrefConstants.frameworkVersion, frameworkVersion); - pref.flush(); - } - } - catch (BackingStoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - - /** - * Load the preferences for a validator. - * - * @param v the validator that is being built up - * @param p the node in the preference tree for the validator, - * e.g. /instance/validator-framework-id/filters/validator-id - * - * @deprecated - */ -// static void loadPreferences(Validator v, Preferences p) throws BackingStoreException { -// v.setBuildValidation(p.getBoolean(PrefConstants.build, true)); -// v.setManualValidation(p.getBoolean(PrefConstants.manual, true)); -// v.setVersion(p.getInt(PrefConstants.version, 1)); -// v.setDelegatingId(p.get(PrefConstants.delegate, null)); -// -// Validator.V2 v2 = v.asV2Validator(); -// if (v2 == null)return; -// if (!p.nodeExists(PrefConstants.groups))return; -// -// Preferences groupNode = p.node(PrefConstants.groups); -// for (String groupName : groupNode.childrenNames()){ -// Preferences group = groupNode.node(groupName); -// String type = group.get(PrefConstants.type, null); -// if (type == null)throw new IllegalStateException(ValMessages.ErrGroupNoType); -// FilterGroup fg = FilterGroup.create(type); -// if (fg == null)throw new IllegalStateException(NLS.bind(ValMessages.ErrGroupInvalidType, type)); -// v2.add(fg); -// -// if (group.nodeExists(PrefConstants.rules)){ -// Preferences ruleNode = group.node(PrefConstants.rules); -// for (String ruleName : ruleNode.childrenNames()){ -// Preferences rule = ruleNode.node(ruleName); -// FilterRule fr = FilterRule.create(rule.get(PrefConstants.ruleType, null)); -// if (fr != null){ -// fr.load(rule); -// fg.add(fr); -// } -// } -// } -// } -// } - - /** - * Save the validator into the preference store. - * - * @param validator - * The validator being saved. - * - * @param root - * The top of the preference tree for validators, i.e. - * /instance/validator-framework-id/vals for workspace validators - * and /vals for project validators. - * - * @param baseValidators - * A map of the validators that are one level higher in the - * storage hierarchy. So if we are updating the preference page - * validators, then this map would be the extension point - * validators. If we are updating a project's validators, then - * this map would be the preference page validators. - */ - static void save(Validator validator, PreferencesWrapper root, Map<String, Validator> baseValidators) throws BackingStoreException { - Validator.V2 v2 = validator.asV2Validator(); - if (v2 == null)return; - - final String id = validator.getId(); - boolean hasNode = root.nodeExists(id); - - if (validator.sameConfig(baseValidators.get(id))){ - if (hasNode){ - PreferencesWrapper vp = root.node(id); - vp.removeNode(); - } - return; - } - if (!validator.isChanged())return; - PreferencesWrapper vp = root.node(id); - if (validator.hasGlobalChanges()){ - Global g = new Global(validator.isManualValidation(), validator.isBuildValidation(), validator.getVersion(), - validator.getDelegatingId()); - vp.put(PrefConstants.global, g.serialize()); - Friend.setMigrated(validator, false); - } - - if (validator.getChangeCountMessages() > 0){ - Collection<MessageSeveritySetting> msgs = validator.getMessageSettings().values(); - if (msgs.size() > 0){ - vp.put(PrefConstants.msgs, Msgs.serialize(msgs)); - } - } - - if (v2.getChangeCountGroups() > 0){ - FilterGroup[] groups = v2.getGroups(); - if (groups.length > 0){ - Serializer ser = new Serializer(500); - for (FilterGroup group : groups)group.save(ser); - vp.put(PrefConstants.groups, ser.toString()); - } - } - } - /** - * Save the validator into the preference store. - * - * @param validator - * The validator being saved. - * - * @param root - * The top of the preference tree for validators, i.e. - * /instance/validator-framework-id/vals for workspace validators - * and /vals for project validators. - * - * @param baseValidators - * A map of the validators that are one level higher in the - * storage hierarchy. So if we are updating the preference page - * validators, then this map would be the extension point - * validators. If we are updating a project's validators, then - * this map would be the preference page validators. - */ - static void save(ValidatorMutable validator, PreferencesWrapper root, Map<String, Validator> baseValidators) throws BackingStoreException { - if (!validator.isV2Validator())return; - - PreferencesWrapper vp = root.node(validator.getId()); - if (validator.sameConfig(baseValidators.get(validator.getId()))){ - vp.removeNode(); - return; - } - if (!validator.isChanged())return; - if (validator.hasGlobalChanges()){ - Global g = new Global(validator.isManualValidation(), validator.isBuildValidation(), validator.getVersion(), - validator.getDelegatingId()); - vp.put(PrefConstants.global, g.serialize()); -// Friend.setMigrated(validator, false); - } - - if (validator.getChangeCountGroups() > 0){ - FilterGroup[] groups = validator.getGroups(); - if (groups.length > 0){ - Serializer ser = new Serializer(500); - for (FilterGroup group : groups)group.save(ser); - vp.put(PrefConstants.groups, ser.toString()); - } - } - } - - public void saveAsPrefs(Validator[] val) { - try { - PreferencesWrapper pref = PreferencesWrapper.getPreferences(null, null); - PreferencesWrapper vals = pref.node(PrefConstants.vals); - Map<String, Validator> base = ExtensionValidators.instance().getMapV2(); - for (Validator v : val)save(v, vals, base); - pref.flush(); - _validators.set(null); - updateListeners(true); - } - catch (BackingStoreException e){ - throw new RuntimeException(e); - } - } - - - /** - * Save the global preferences and the validators. - */ - public synchronized void savePreferences(GlobalPreferences gp, Validator[] validators){ - try { - PreferencesWrapper prefs = PreferencesWrapper.getPreferences(null, null); - savePreferences(prefs, gp); - PreferencesWrapper vals = prefs.node(PrefConstants.vals); - - Map<String, Validator> base = ExtensionValidators.instance().getMapV2(); - for (Validator v : validators)save(v, vals, base); - prefs.flush(); - _validators.set(null); - updateListeners(true); - } - catch (BackingStoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - - /** - * Save the global preferences and the validators. - */ - public synchronized void savePreferences(GlobalPreferences gp, ValidatorMutable[] validators, Boolean persist){ - try { - PreferencesWrapper prefs = PreferencesWrapper.getPreferences(null, persist); - savePreferences(prefs, gp); - PreferencesWrapper vals = prefs.node(PrefConstants.vals); - Map<String, Validator> base = ExtensionValidators.instance().getMapV2(); - for (ValidatorMutable v : validators)save(v, vals, base); - - prefs.flush(); - _validators.set(null); - updateListeners(true); - } - catch (BackingStoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - - /** - * Save the V1 preferences, so that the old validators continue to work. - */ - public static void saveV1Preferences(ValidatorMutable[] validators, Boolean persistent){ - try { - GlobalConfiguration gc = ConfigurationManager.getManager().getGlobalConfiguration(); - gc.setEnabledManualValidators(getEnabledManualValidators(validators)); - gc.setEnabledBuildValidators(getEnabledBuildValidators(validators)); - - gc.passivate(); - gc.store(persistent); - } - catch (InvocationTargetException e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - - /** - * Answer all the V1 validators that are manually enabled. - * @return - */ - private static ValidatorMetaData[] getEnabledManualValidators(ValidatorMutable[] validators) { - List<ValidatorMetaData> list = new LinkedList<ValidatorMetaData>(); - for (ValidatorMutable v : validators){ - if (v.isManualValidation() && v.isV1Validator())list.add(v.getVmd()); - } - ValidatorMetaData[] result = new ValidatorMetaData[list.size()]; - list.toArray(result); - return result; - } - - /** - * Answer all the V1 validators that are enabled for build. - * @return - */ - private static ValidatorMetaData[] getEnabledBuildValidators(ValidatorMutable[] validators) { - List<ValidatorMetaData> list = new LinkedList<ValidatorMetaData>(); - for (ValidatorMutable v : validators){ - if (v.isBuildValidation() && v.isV1Validator())list.add(v.getVmd()); - } - ValidatorMetaData[] result = new ValidatorMetaData[list.size()]; - list.toArray(result); - return result; - } - - - /** - * Save the global preferences and the validators. - */ - public synchronized void savePreferences(){ - try { - GlobalPreferences gp = ValManager.getDefault().getGlobalPreferences(); - PreferencesWrapper prefs = PreferencesWrapper.getPreferences(null, null); - savePreferences(prefs, gp); - prefs.flush(); - updateListeners(true); - } - catch (BackingStoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - - /** - * Save the global preferences and the validators. - */ - private void savePreferences(PreferencesWrapper prefs, GlobalPreferences gp){ - prefs.putBoolean(PrefConstants.saveAuto, gp.getSaveAutomatically()); - prefs.putBoolean(PrefConstants.suspend, gp.getDisableAllValidation()); - prefs.putLong(PrefConstants.stateTS, gp.getStateTimeStamp()); - prefs.putBoolean(PrefConstants.confirmDialog, gp.getConfirmDialog()); - prefs.putBoolean(PrefConstants.override, gp.getOverride()); - prefs.putInt(PrefConstants.frameworkVersion, ValPrefManagerGlobal.frameworkVersion); - } - - /** - * Update any message preferences in the map. - * @param validator - * @param settings - */ - public void loadMessages(Validator validator, Map<String, MessageSeveritySetting> settings) { - PreferencesWrapper pref = PreferencesWrapper.getPreferences(null, null); - try { - loadMessageSettings(validator, settings, pref); - } - catch (BackingStoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - - /** - * Load the message preferences for the validator into the map. - * - * @param val - * @param settings - * @param root the root of the preference store - */ - static void loadMessageSettings(Validator val, Map<String, MessageSeveritySetting> settings, PreferencesWrapper root) - throws BackingStoreException { - if (!root.nodeExists(PrefConstants.vals))return; - - PreferencesWrapper vals = root.node(PrefConstants.vals); - if (!vals.nodeExists(val.getId()))return; - - PreferencesWrapper valPrefs = vals.node(val.getId()); - String msgs = valPrefs.get(PrefConstants.msgs, ""); //$NON-NLS-1$ - if (msgs.length() == 0)return; - - Map<String, MessageSeveritySetting.Severity> map = Msgs.deserialize(msgs); - - for (Map.Entry<String, MessageSeveritySetting.Severity> me : map.entrySet()){ - MessageSeveritySetting ms = settings.get(me.getKey()); - if (ms != null)ms.setCurrent(me.getValue()); - } - } - - /** - * Save whether the validator is enabled or not. - * @param validator - * @param prefs up to the filter part of the preference tree - */ -// private void saveShallowPreference(Validator validator, Preferences prefs) { -// if (validator.asV2Validator() == null)return; -// Preferences val = prefs.node(validator.getId()); -// val.putBoolean(PrefConstants.build, validator.isBuildValidation()); -// val.putBoolean(PrefConstants.manual, validator.isManualValidation()); -// val.putInt(PrefConstants.version, validator.getVersion()); -// } - -// /** -// * Load the customized message settings from the preference store. -// * @param messageSettings -// */ -// public void loadMessageSettings(Validator val, MessageCategory[] messageSettings) { -// try { -// loadMessageSettings(val, messageSettings, ValidationFramework.getDefault().getPreferenceStore()); -// } -// catch (Exception e){ -// ValidationPlugin.getPlugin().handleException(e); -// } -// } - - private final static class Global { - private final boolean _manual; - private final boolean _build; - private final int _version; - private final String _delegating; - - public Global(String value){ - Deserializer d = new Deserializer(value); - _manual = d.getBoolean(); - _build = d.getBoolean(); - _version = d.getInt(); - _delegating = d.hasNext() ? d.getString() : null; - } - - public Global(boolean manual, boolean build, int version, String delegating){ - _manual = manual; - _build = build; - _version = version; - _delegating = delegating; - } - - public String serialize(){ - Serializer s = new Serializer(50); - s.put(_manual); - s.put(_build); - s.put(_version); - if (_delegating != null)s.put(_delegating); - return s.toString(); - } - - public boolean isManual() { - return _manual; - } - - public boolean isBuild() { - return _build; - } - - public int getVersion() { - return _version; - } - - public String getDelegating() { - return _delegating; - } - } - - private final static class Msgs { - public static String serialize(Collection<MessageSeveritySetting> messages){ - Serializer s = new Serializer(100); - for (MessageSeveritySetting ms : messages){ - s.put(ms.getId()); - s.put(ms.getCurrent().ordinal()); - } - return s.toString(); - } - - /** - * Answer a map for all the messages. - * The key is the message id and the value is the current setting for that message - * @param v - * @return - */ - public static Map<String, MessageSeveritySetting.Severity> deserialize(String v){ - Map<String, MessageSeveritySetting.Severity> map = new HashMap<String, MessageSeveritySetting.Severity>(10); - Deserializer d = new Deserializer(v); - while(d.hasNext()){ - String id = d.getString(); - int sev = d.getInt(); - map.put(id, MessageSeveritySetting.Severity.values()[sev]); - } - return map; - } - } - - /** - * Store the singleton for the ValPrefManagerGlobal. This approach is used to avoid having to synchronize the - * ValPrefManagerGlobal.getDefault() method. - * - * @author karasiuk - * - */ - private final static class Singleton { - final static ValPrefManagerGlobal valPrefManagerGlobal = new ValPrefManagerGlobal(); - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerProject.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerProject.java deleted file mode 100644 index c28b0318a..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValPrefManagerProject.java +++ /dev/null @@ -1,388 +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.wst.validation.internal; - -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.resources.IProject; -import org.eclipse.wst.validation.Friend; -import org.eclipse.wst.validation.IMutableValidator; -import org.eclipse.wst.validation.MessageSeveritySetting; -import org.eclipse.wst.validation.MutableProjectSettings; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.Validator.V2; -import org.eclipse.wst.validation.internal.model.ProjectPreferences; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; -import org.osgi.service.prefs.BackingStoreException; - -/** - * A class that knows how to manage the project level persisted validation settings. - * @author karasiuk - * - */ -public final class ValPrefManagerProject { - - private final IProject _project; - private final static List<IValChangedListener> _listeners = new LinkedList<IValChangedListener>(); - - /** - * The validators that are in the project preference file, but have - * only been configured to the global preference level. That is they have not had - * any project level customizations applied yet. - */ - private List<Validator> _validators; - - public ValPrefManagerProject(IProject project){ - assert project != null; - _project = project; - } - - public static void addListener(IValChangedListener listener){ - if (_listeners.contains(listener))return; - _listeners.add(listener); - } - - public static void removeListener(IValChangedListener listener){ - _listeners.remove(listener); - } - - private static void updateListeners(IProject project){ - for (IValChangedListener cl : _listeners)cl.validatorsForProjectChanged(project, true); - } - - - /** - * Answer whether or not this project has validation settings. - * - * @return true if it has settings. This does not mean that the settings are enabled, only that it - * has settings. - * - * @deprecated - */ - public boolean hasProjectSpecificSettings(){ - PreferencesWrapper pref = getPreferences(null); - - if (pref == null)return false; - return true; - } - - /** - * Answer the v2 validators that have been overridden by the project - * preferences. The validators will not have the preference store's - * customizations applied yet. The purpose of this method, is to identify the subset of validators - * that may later be configured. - * - * @param baseValidators - * V2 validators from the extension points, and customized by any - * global preferences. - */ - public List<Validator> getValidators(Map<String, Validator> baseValidators) throws BackingStoreException { - List<Validator> vals = _validators; - if (vals == null){ - vals = loadValidators(baseValidators); - _validators = vals; - } - return vals; - } - - /** - * Load the validators from the preference store. The validators will not have the preference store's - * customizations applied yet. The purpose of this method, is to identify the subset of validators - * that may later be configured. - * - * @param baseValidators - * V2 validators from the extension points, and customized by any - * global preferences. - * @return the validators that are in the project preference file, but have - * only been configured to the global preference level. That is they have not had - * any project level customizations applied yet. - */ - private List<Validator> loadValidators(Map<String, Validator> baseValidators) throws BackingStoreException { - List<Validator> list = new LinkedList<Validator>(); - PreferencesWrapper pref = getPreferences(null); - if (pref.nodeExists(PrefConstants.vals)){ - PreferencesWrapper vals = pref.node(PrefConstants.vals); - for (String id : vals.childrenNames()){ - Validator base = baseValidators.get(id); - Validator v = ValPrefManagerGlobal.loadValidator(id, vals, base); - if (v != null){ - V2 v2 = v.asV2Validator(); - if (v2 != null)v2.setLevel(Validator.Level.Project); - list.add(v); - } - } - } - return list; - } - - /** - * Answer the setting of the getOverride field. - */ - public boolean getOverride(){ - PreferencesWrapper pref = getPreferences(null); - - if (!pref.nodeExists())return ProjectPreferences.DefaultOverride; - - int version = pref.getInt(PrefConstants.frameworkVersion, 0); - if (version == 0){ - try { - ProjectConfiguration pc = ConfigurationManager.getManager().getProjectConfiguration(_project); - return pc.getDoesProjectOverride(); - } - catch (InvocationTargetException e){ - // eat it, if it fails we just go with the defaults - } - } - return pref.getBoolean(PrefConstants.override, ProjectPreferences.DefaultOverride); - } - - private ProjectPreferences migrateFromBeforeWTP30(IProject project, Map<String, Validator> baseValidators) { - try { - ProjectConfiguration pc = ConfigurationManager.getManager().getProjectConfiguration(project); - - List<Validator> list = migrateFromBeforeWTP30(baseValidators, pc); - Validator[] vals = new Validator[list.size()]; - list.toArray(vals); - return new ProjectPreferences(project, pc.getDoesProjectOverride(), pc.isDisableAllValidation(), vals); - } - catch (InvocationTargetException e){ - // eat it, if it fails we just go with the defaults - } - return new ProjectPreferences(project); - } - - private List<Validator> migrateFromBeforeWTP30(Map<String, Validator> baseValidators, ProjectConfiguration pc) - throws InvocationTargetException { - - Set<String> build = pc.getEnabledBuildlValidators(); - Set<String> manual = pc.getEnabledManualValidators(); - - List<Validator> list = new LinkedList<Validator>(); - for (Validator v : baseValidators.values()){ - V2 v2 = v.asV2Validator(); - if (v2 != null){ - boolean isBuild = build == null || build.contains(v2.getValidatorClassname()); - boolean isManual = manual == null || manual.contains(v2.getValidatorClassname()); - if ((v.isBuildValidation() != isBuild) || (v.isManualValidation() != isManual)){ - V2 copy = v2.copy().asV2Validator(); - copy.setBuildValidation(isBuild); - copy.setManualValidation(isManual); - copy.setLevel(Validator.Level.Project); - Friend.setMigrated(copy, true); - list.add(copy); - } - } - } - return list; - } - - - /** - * Answer the project preferences from the preference store. - * @return null if the project does not have any specific preferences. - */ - public ProjectPreferences loadProjectPreferences(IProject project, Map<String, Validator> baseValidators) - throws BackingStoreException { - - PreferencesWrapper pref = getPreferences(null); - - if (pref == null)return null; - int version = pref.getInt(PrefConstants.frameworkVersion, 0); - if (version == 0){ - // This means that we have a project that is before WTP 3.0 - return migrateFromBeforeWTP30(project, baseValidators); - } - - if (version != ValPrefManagerGlobal.frameworkVersion)ValPrefManagerGlobal.migrate(version, pref); - - if (!pref.nodeExists(PrefConstants.vals)){ - return new ProjectPreferences(project, pref.getBoolean(PrefConstants.override, ProjectPreferences.DefaultOverride), - pref.getBoolean(PrefConstants.suspend, ProjectPreferences.DefaultSuspend), new Validator[0]); - } - - PreferencesWrapper vp = pref.node(PrefConstants.vals); - List<Validator> list = new LinkedList<Validator>(); - for (String id : vp.childrenNames()){ - Validator base = baseValidators.get(id); - Validator v = ValPrefManagerGlobal.loadValidator(id, vp, base); - if (v != null){ - V2 v2 = v.asV2Validator(); - if (v2 != null)v2.setLevel(Validator.Level.Project); - list.add(v); - } - } - Validator[] vals = new Validator[list.size()]; - list.toArray(vals); - return new ProjectPreferences(project, pref.getBoolean(PrefConstants.override, ProjectPreferences.DefaultOverride), - pref.getBoolean(PrefConstants.suspend, ProjectPreferences.DefaultSuspend), vals); - } - - private PreferencesWrapper getPreferences(Boolean persist) { - return PreferencesWrapper.getPreferences(_project, persist); - } - - public void savePreferences(ProjectPreferences projectPreferences) { - Validator[] validators = projectPreferences.getValidators(); - PreferencesWrapper pref = getPreferences(null); - pref.putBoolean(PrefConstants.suspend, projectPreferences.getSuspend()); - pref.putBoolean(PrefConstants.override, projectPreferences.getOverride()); - pref.putInt(PrefConstants.frameworkVersion, ValPrefManagerGlobal.frameworkVersion); - PreferencesWrapper vals = pref.node(PrefConstants.vals); - try { - Validator[] workspaceVals = ValManager.getDefault().getValidators(); - Map<String, Validator> base = new HashMap<String, Validator>(workspaceVals.length); - for (Validator v : workspaceVals)base.put(v.getId(), v); - for (Validator v : validators)ValPrefManagerGlobal.save(v, vals, base); - pref.flush(); - ProjectConfiguration pc = ConfigurationManager.getManager() - .getProjectConfiguration(projectPreferences.getProject()); - pc.setEnabledBuildValidators(getEnabledBuildValidators(validators)); - pc.setEnabledManualValidators(getEnabledManualValidators(validators)); - pc.passivate(); - pc.store(); - updateListeners(_project); - } - catch (Exception e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - - public void savePreferences(ProjectPreferences projectPreferences, ValidatorMutable[] validators) { - PreferencesWrapper pref = getPreferences(null); - pref.putBoolean(PrefConstants.suspend, projectPreferences.getSuspend()); - pref.putBoolean(PrefConstants.override, projectPreferences.getOverride()); - pref.putInt(PrefConstants.frameworkVersion, ValPrefManagerGlobal.frameworkVersion); - try { - savePreferences(validators, false, null); - pref.flush(); - updateListeners(_project); - } - catch (Exception e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - - public void savePreferences(MutableProjectSettings settings, Boolean persist){ - IProject project = settings.getProject(); - PreferencesWrapper pref = PreferencesWrapper.getPreferences(project, persist); - pref.putBoolean(PrefConstants.suspend, settings.getSuspend()); - pref.putBoolean(PrefConstants.override, settings.getOverride()); - pref.putInt(PrefConstants.frameworkVersion, ValPrefManagerGlobal.frameworkVersion); - - IMutableValidator[] vms = settings.getValidators(); - ValidatorMutable[] validators = new ValidatorMutable[vms.length]; - for (int i=0; i<vms.length;i++)validators[i] = (ValidatorMutable)vms[i]; - - try { - savePreferences(validators, false, persist); - pref.flush(); - updateListeners(project); - } - catch (Exception e){ - if (project.isAccessible())ValidationPlugin.getPlugin().handleException(e); - } - } - - public void savePreferences(ValidatorMutable[] validators, boolean flush, Boolean persist){ - PreferencesWrapper pref = getPreferences(persist); - pref.putInt(PrefConstants.frameworkVersion, ValPrefManagerGlobal.frameworkVersion); - PreferencesWrapper vals = pref.node(PrefConstants.vals); - try { - Validator[] workspaceVals = ValManager.getDefault().getValidators(); - Map<String, Validator> base = new HashMap<String, Validator>(workspaceVals.length); - for (Validator v : workspaceVals)base.put(v.getId(), v); - for (ValidatorMutable v : validators)ValPrefManagerGlobal.save(v, vals, base); - ProjectConfiguration pc = ConfigurationManager.getManager().getProjectConfiguration(_project); - pc.setEnabledBuildValidators(getEnabledBuildValidators(validators)); - pc.setEnabledManualValidators(getEnabledManualValidators(validators)); - pc.passivate(); - pc.store(); - if (flush){ - pref.flush(); - updateListeners(_project); - } - } - catch (Exception e){ - ValidationPlugin.getPlugin().handleException(e); - } - - } - - /** - * Answer all the V1 validators that are enabled for build. - * @return - */ - private Set<ValidatorMetaData> getEnabledBuildValidators(Validator[] validators) { - Set<ValidatorMetaData> set = new HashSet<ValidatorMetaData>(50); - for (Validator v : validators){ - if (v.isBuildValidation()){ - Validator.V1 v1 = v.asV1Validator(); - if (v1 != null)set.add(v1.getVmd()); - } - } - return set; - } - - /** - * Answer all the V1 validators that are enabled for build. - * @return - */ - private Set<ValidatorMetaData> getEnabledBuildValidators(ValidatorMutable[] validators) { - Set<ValidatorMetaData> set = new HashSet<ValidatorMetaData>(50); - for (ValidatorMutable v : validators){ - if (v.isBuildValidation() && v.isV1Validator())set.add(v.getVmd()); - } - return set; - } - - /** - * Answer all the V1 validators that are enabled for manual validation. - * @return - */ - private Set<ValidatorMetaData> getEnabledManualValidators(Validator[] validators) { - Set<ValidatorMetaData> set = new HashSet<ValidatorMetaData>(50); - for (Validator v : validators){ - if (v.isManualValidation()){ - Validator.V1 v1 = v.asV1Validator(); - if (v1 != null)set.add(v1.getVmd()); - } - } - return set; - } - - /** - * Answer all the V1 validators that are enabled for manual validation. - * @return - */ - private Set<ValidatorMetaData> getEnabledManualValidators(ValidatorMutable[] validators) { - Set<ValidatorMetaData> set = new HashSet<ValidatorMetaData>(50); - for (ValidatorMutable v : validators){ - if (v.isManualValidation() && v.isV1Validator())set.add(v.getVmd()); - } - return set; - } - - public void loadMessages(Validator validator, Map<String, MessageSeveritySetting> settings) { - try { - ValPrefManagerGlobal.loadMessageSettings(validator, settings, getPreferences(null)); - } - catch (BackingStoreException e){ - ValidationPlugin.getPlugin().handleException(e); - } - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValProperty.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValProperty.java deleted file mode 100644 index fd001dc9e..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValProperty.java +++ /dev/null @@ -1,53 +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.wst.validation.internal; - -import java.util.BitSet; - -/** - * A resource session property, that is used to improve the performance of the validation framework. This is placed - * on each resource and it enables the framework to quickly determine if the resource needs to be processed. - * @author karasiuk - * - */ -public class ValProperty { -/* - * I did some performance measurements on the IResource#setSessionProperty() and IResource#getSessionProperty() - * methods, and they were very fast. I used a very large workspace (over 17,000) resources, and you could set (or get) - * a property on all the resources in under 100ms. - */ - - private int _configNumber; - private BitSet _configSet = new BitSet(100); - - private int _validationNumber; - private BitSet _validationSet = new BitSet(100); - - public int getConfigNumber() { - return _configNumber; - } - public void setConfigNumber(int configNumber) { - _configNumber = configNumber; - } - public BitSet getConfigSet() { - return _configSet; - } - public int getValidationNumber() { - return _validationNumber; - } - public void setValidationNumber(int validationNumber) { - _validationNumber = validationNumber; - } - public BitSet getValidationSet() { - return _validationSet; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValType.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValType.java deleted file mode 100644 index 8a97136df..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValType.java +++ /dev/null @@ -1,24 +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.wst.validation.internal; - -/** - * Type of validation. Build or Manual? - * @author karasiuk - * - */ -public enum ValType { - /** The validation is triggered via a resource change and the build process. */ - Build, - - /** The user manually requested the validation. */ - Manual, -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationResultSummary.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationResultSummary.java deleted file mode 100644 index 9e91217cb..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationResultSummary.java +++ /dev/null @@ -1,42 +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.wst.validation.internal; - -/** - * An immutable object that holds a summary of the validation. - * @author karasiuk - * - */ -public final class ValidationResultSummary { - - private final int _error; - private final int _warning; - private final int _info; - - public ValidationResultSummary(int error, int warning, int info){ - _error = error; - _warning = warning; - _info = info; - } - - public int getSeverityError() { - return _error; - } - - public int getSeverityWarning() { - return _warning; - } - - public int getSeverityInfo() { - return _info; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationRunner.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationRunner.java deleted file mode 100644 index 01bf29725..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidationRunner.java +++ /dev/null @@ -1,151 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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.wst.validation.internal; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.resources.IncrementalProjectBuilder; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.internal.model.IValidatorVisitor; - -/** - * Run the validators on a selected set of resources. - * <p> - * This is used to run manual validations (i.e. the user selects the Validate menu item), - * or it is invoked programmatically by a third party through the ValidationFramework API. - * It is not used for the build based invocation. - * </p> - * @author karasiuk - * - */ -public final class ValidationRunner implements IWorkspaceRunnable { - - private Map<IProject, Set<IResource>> _projects; - private ValType _valType; - private ValOperation _valOperation; - - /** - * Validate the selected projects and/or resources. - * - * @param projects - * The selected projects. The key is an IProject and the value is - * the Set of IResources that were selected. Often this will be - * every resource in the project. - * - * @param valType - * The type of validation that has been requested. - * - * @param monitor - * Progress monitor. - * - * @param atomic - * Run as an atomic workspace operation? - */ - public static ValOperation validate(Map<IProject, Set<IResource>> projects, ValType valType, - IProgressMonitor monitor, boolean atomic) throws CoreException{ - ValidationRunner me = new ValidationRunner(projects, valType); - if (atomic)ResourcesPlugin.getWorkspace().run(me, null, IWorkspace.AVOID_UPDATE, monitor); - else me.execute(monitor); - return me._valOperation; - } - - /** - * Validate the selected file. This is a convenience method, it simply calls the more flexible - * validate with Map method. - * - * @param file - * The file to be validated. - * - * @param valType - * The type of validation that has been requested. - * - * @param monitor - * Progress monitor. - * - * @param atomic - * Run as an atomic workspace operation? - */ - public static ValOperation validate(IFile file, ValType valType, IProgressMonitor monitor, boolean atomic) throws CoreException{ - final Map<IProject, Set<IResource>> map = new HashMap<IProject, Set<IResource>>(1); - - Set<IResource> set = new HashSet<IResource>(1); - set.add(file); - map.put(file.getProject(), set); - return validate(map, valType, monitor, atomic); - } - - private ValidationRunner(Map<IProject, Set<IResource>> projects, ValType valType){ - _projects = projects; - _valType = valType; - - } - - private ValOperation execute(IProgressMonitor monitor){ - _valOperation = new ValOperation(); - ValManager manager = ValManager.getDefault(); - - IValidatorVisitor startingVisitor = new IValidatorVisitor(){ - public void visit(Validator validator, IProject project, ValType valType, - ValOperation operation, IProgressMonitor monitor) { - validator.validationStarting(project, operation.getState(), monitor); - } - }; - - IValidatorVisitor finishedVisitor = new IValidatorVisitor(){ - - public void visit(Validator validator, IProject project, ValType valType, - ValOperation operation, IProgressMonitor monitor) { - - validator.validationFinishing(project, operation.getState(), monitor); - } - }; - - manager.accept(startingVisitor, null, _valType, _valOperation, monitor); - - for (Map.Entry<IProject, Set<IResource>> me : _projects.entrySet()){ - if (monitor.isCanceled()){ - _valOperation.setCanceled(true); - return _valOperation; - } - IProject project = me.getKey(); - manager.accept(startingVisitor, project, _valType, _valOperation, monitor); - for (IResource resource : me.getValue()){ - try { - manager.validate(project, resource, IResourceDelta.NO_CHANGE, _valType, - IncrementalProjectBuilder.AUTO_BUILD, _valOperation, monitor); - } - catch (ResourceUnavailableError error){ - // if the resource is no longer available, we can't validate it, so we should just move on. - } - } - manager.accept(finishedVisitor, project, _valType, _valOperation, monitor); - } - manager.accept(finishedVisitor, null, _valType, _valOperation, monitor); - return _valOperation; - } - - public void run(IProgressMonitor monitor) throws CoreException { - execute(monitor); - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorExtensionReader.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorExtensionReader.java deleted file mode 100644 index 108e06683..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorExtensionReader.java +++ /dev/null @@ -1,373 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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.wst.validation.internal; - -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IContributor; -import org.eclipse.core.runtime.IExtension; -import org.eclipse.core.runtime.IExtensionPoint; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.validation.MessageSeveritySetting; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.Validator.V2; -import org.eclipse.wst.validation.internal.model.FilterGroup; -import org.eclipse.wst.validation.internal.model.FilterRule; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -/** - * Process the validator (version 2) extension point. - * - * @author karasiuk - * - */ -public class ValidatorExtensionReader { - - private static ValidatorExtensionReader _me = new ValidatorExtensionReader(); - - public static ValidatorExtensionReader getDefault(){ - return _me; - } - - private ValidatorExtensionReader(){} - - /** - * Process the v2 extensions, returning all the v2 validators. - */ - Collection<Validator> process() { - Map<String,Validator> map = new HashMap<String, Validator>(100); - IExtensionPoint extensionPoint = getExtensionPoint(); - if (extensionPoint == null)return map.values(); - - for (IExtension ext : extensionPoint.getExtensions()){ - for (IConfigurationElement validator : ext.getConfigurationElements()){ - String id = ext.getUniqueIdentifier(); - if (Tracing.isEnabled(id)){ - Validator v = processValidator(validator, id, ext.getLabel(), null); - if (v != null)map.put(v.getId(),v); - } - } - } - - extensionPoint = getExtensionPointExclude(); - if (extensionPoint != null){ - for (IExtension ext : extensionPoint.getExtensions()){ - for (IConfigurationElement validator : ext.getConfigurationElements()){ - String id = validator.getAttribute(ExtensionConstants.Exclude.id); - Validator v = map.get(id); - V2 v2 = null; - if (v != null)v2 = v.asV2Validator(); - - if (v2 == null){ - String msg = NLS.bind("Plug-in configuration error, extension {0} references validator id {1} but this id does not exist.", //$NON-NLS-1$ - extensionPoint.getUniqueIdentifier(), id); - CoreException ex = new CoreException(new Status(IStatus.ERROR, ValidationPlugin.PLUGIN_ID, msg)); - ValidationPlugin.getPlugin().handleException(ex); - } - else { - for (IConfigurationElement exclude : validator.getChildren()){ - FilterGroup fg = null; - try { - fg = createFilterGroup(exclude); - } - catch (Exception e){ - ValidationPlugin.getPlugin().handleException(e); - IContributor contrib = validator.getContributor(); - String message = NLS.bind(ValMessages.ErrConfig, contrib.getName()); - ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, message); - } - if (fg != null && fg.isExclude()){ - mergeExcludeGroup(v2, fg); - } - } - } - } - } - - } - return map.values(); - - } - - /** - * Merge the rules from the filter group into the current exclude group, creating a current exclude - * group if need be. - * @param v2 - * @param fg - */ - private void mergeExcludeGroup(V2 v2, FilterGroup fg){ - FilterGroup existing = null; - for (FilterGroup group : v2.getGroups()){ - if (group.isExclude()){ - existing = group; - break; - } - } - if (existing == null)v2.add(fg); - else { - List<FilterRule> rules = new LinkedList<FilterRule>(); - for (FilterRule rule : existing.getRules())rules.add(rule); - - for (FilterRule rule : fg.getRules())rules.add(rule); - - FilterRule[] filterRules = new FilterRule[rules.size()]; - rules.toArray(filterRules); - FilterGroup merged = FilterGroup.create(existing.isExclude(), filterRules); - - v2.replaceFilterGroup(existing, merged); - } - } - - /** - * Process the validator element in a validator extension. - * - * @param validator - * The validator element. - * - * @param deep - * If true load all the configuration elements for each - * validator, if false do a shallow load, where only the - * validator class, id and name's are loaded. - * - * @param project - * The project that you are defined in. This can be null which - * means that you are a global validator. - * - * @return a configured validator or null if there was an error. - */ - private Validator processValidator(IConfigurationElement validator, String id, String label, IProject project) { - Validator.V2 v = null; - try { - v = Validator.create(validator, project).asV2Validator(); - v.setLevel(Validator.Level.Extension); - v.setId(id); - v.setName(label); - v.setBuildValidation(getAttribute(validator, ExtensionConstants.build, true)); - v.setManualValidation(getAttribute(validator, ExtensionConstants.manual, true)); - v.setMarkerId(validator.getAttribute(ExtensionConstants.markerId)); - v.setVersion(getAttribute(validator, ExtensionConstants.version, 1)); - v.setSourceId(validator.getAttribute(ExtensionConstants.sourceId)); - IConfigurationElement[] children = validator.getChildren(); - for (IConfigurationElement child : children)processIncludeAndExcludeElement(v, child); - } - catch (Exception e){ - ValidationPlugin.getPlugin().handleException(e); - IContributor contrib = validator.getContributor(); - String message = NLS.bind(ValMessages.ErrConfig, contrib.getName()); - ValidationPlugin.getPlugin().logMessage(IStatus.ERROR, message); - } - return v; - } - - /** - * Answer all the messages that this validator has defined. - * @param v - * @return an empty list if the validator did not define any messages. - */ - public List<MessageSeveritySetting> addMessages(Validator v){ - List<MessageSeveritySetting> list = new LinkedList<MessageSeveritySetting>(); - IExtensionPoint extensionPoint = getExtensionPoint(); - if (extensionPoint == null)return list; - IExtension ext = extensionPoint.getExtension(v.getId()); - if (ext == null)return list; - - for (IConfigurationElement elem : ext.getConfigurationElements()){ - for (IConfigurationElement ce : elem.getChildren(ExtensionConstants.MessageCategory.name)){ - list.add(processMessage(ce)); - } - } - - return list; - } - - /** - * Answer the extension point for the v2 validators. - * - * @return null if there is a problem or no extensions. - */ - private IExtensionPoint getExtensionPoint() { - IExtensionRegistry registry = Platform.getExtensionRegistry(); - return registry.getExtensionPoint(ValidationPlugin.PLUGIN_ID, ExtensionConstants.validator); - } - - /** - * Answer the extension point for adding exclusion filters. This is where another validator can - * further restrict an existing validator. - * - * @return null if there is a problem or no extensions. - */ - private IExtensionPoint getExtensionPointExclude() { - IExtensionRegistry registry = Platform.getExtensionRegistry(); - return registry.getExtensionPoint(ValidationPlugin.PLUGIN_ID, ExtensionConstants.excludeExtension); - } - - /** - * Process a message element for the validator, by creating a MessageCategory for it. - * - * @param ce a MessageCategory element. - */ - private MessageSeveritySetting processMessage(IConfigurationElement ce) { - String s = ce.getAttribute(ExtensionConstants.MessageCategory.severity); - MessageSeveritySetting.Severity sev = null; - if (ExtensionConstants.MessageCategory.sevError.equals(s))sev = MessageSeveritySetting.Severity.Error; - else if (ExtensionConstants.MessageCategory.sevWarning.equals(s))sev = MessageSeveritySetting.Severity.Warning; - else if (ExtensionConstants.MessageCategory.sevIgnore.equals(s))sev = MessageSeveritySetting.Severity.Ignore; - - return new MessageSeveritySetting(ce.getAttribute(ExtensionConstants.MessageCategory.id), - ce.getAttribute(ExtensionConstants.MessageCategory.label), sev); - } - - /** - * Process the include and exclude elements. - * - * @param v The validator that we are building up. - * @param group The children of the validator tag. This may included include and exclude elements. - * Other elements are ignored. - */ - private void processIncludeAndExcludeElement(Validator.V2 v, IConfigurationElement group) { - FilterGroup fg = createFilterGroup(group); - if (fg != null)v.add(fg); - } - - /** - * Process an include or exclude element, returning a filter group for it. - * - * @param group - * An include, exclude or some other element. Only include and - * exclude elements are processed, other types are ignored. - * - * @return a filter group that corresponds to the include or exclude - * element, or null if the element was not an include or exclude - * element. - */ - private FilterGroup createFilterGroup(IConfigurationElement group){ - String name = group.getName(); - if (!FilterGroup.isKnownName(name))return null; - - - IConfigurationElement[] rules = group.getChildren(ExtensionConstants.rules); - // there should only be one - List<FilterRule> list = new LinkedList<FilterRule>(); - for (int i=0; i<rules.length; i++){ - IConfigurationElement[] r = rules[i].getChildren(); - for(int j=0; j<r.length; j++){ - list.add(processRule(r[j])); - } - } - FilterRule[] filterRules = new FilterRule[list.size()]; - list.toArray(filterRules); - return FilterGroup.create(name, filterRules); - } - - /** - * Process a rule in one of the rule groups. - * - * @param rule a rule in the group, like fileext. - */ - private FilterRule processRule(IConfigurationElement rule) { - FilterRule fr = FilterRule.create(rule); - if (fr == null){ - String contributor = ""; //$NON-NLS-1$ - String name = ""; //$NON-NLS-1$ - try { - contributor = rule.getDeclaringExtension().getContributor().getName(); - name = rule.getName(); - } - catch (Exception e){ - // eat it - } - throw new IllegalStateException(NLS.bind(ValMessages.ErrFilterRule, contributor, name)); - } - return fr; - } - - /** - * Determine if any of the validators need to be migrated, and if so answer a new - * Validator array. - * - * @param validators the existing validators (from the preferences). - * - * @return null if no validators needed to be migrated. - */ - Validator[] migrate(Validator[] validators, IProject project) { - int count = 0; - Map<String, Validator> map = new HashMap<String, Validator>(validators.length); - for (Validator v : validators)map.put(v.getId(), v); - - IExtensionPoint extensionPoint = getExtensionPoint(); - if (extensionPoint == null)return null; - - for (IExtension ext : extensionPoint.getExtensions()){ - for (IConfigurationElement validator : ext.getConfigurationElements()){ - Validator v = processValidator(validator, ext.getUniqueIdentifier(), ext.getLabel(), project); - if (v == null)continue; - Validator old = map.get(v.getId()); - if (old == null || old.getVersion() < v.getVersion()){ - //TODO we may be replacing user preferences, at some point we may want to do a real migration. - map.put(v.getId(), v); - count++; - } - } - } - - if (count > 0){ - Validator[] vals = new Validator[map.size()]; - map.values().toArray(vals); - return vals; - } - return null; - } - - private boolean getAttribute(IConfigurationElement element, String name, boolean dft){ - String v = element.getAttribute(name); - if (v == null)return dft; - if ("true".equalsIgnoreCase(v))return true; //$NON-NLS-1$ - if ("false".equalsIgnoreCase(v))return false; //$NON-NLS-1$ - return dft; - } - - private int getAttribute(IConfigurationElement element, String name, int dft){ - String v = element.getAttribute(name); - if (v == null)return dft; - try { - return Integer.parseInt(v); - } - catch (Exception e){ - // eat it. - } - return dft; - } - -// /** -// * This method is only used for debugging. -// * @param elem -// */ -// private static void dump(IConfigurationElement elem){ -// String name = elem.getName(); -// String[] attribs = elem.getAttributeNames(); -// String[] vals = new String[attribs.length]; -// for (int i=0; i<vals.length; i++)vals[i] = elem.getAttribute(attribs[i]); -// String v = elem.getValue(); -// IConfigurationElement[] children = elem.getChildren(); -// for (int i=0; i<children.length; i++)dump(children[i]); -// } -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorGroupExtensionReader.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorGroupExtensionReader.java deleted file mode 100644 index 62543f7bd..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorGroupExtensionReader.java +++ /dev/null @@ -1,140 +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.wst.validation.internal; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtension; -import org.eclipse.core.runtime.IExtensionPoint; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.validation.IValidatorGroupListener; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -/** - * Process the validator group (for use with validator version 2 only) extension point. - * - * @author nitin - * - */ -public class ValidatorGroupExtensionReader { - - private static final String DOT = "."; //$NON-NLS-1$ - private static ValidatorGroupExtensionReader _instance; - - public static ValidatorGroupExtensionReader getDefault() { - if (_instance == null)_instance = new ValidatorGroupExtensionReader(); - return _instance; - } - - /** - * Map of group IDs to configuration elements - */ - private Map<String, List<IConfigurationElement>> _map; - - /** - * Map of group ID's to resolved configuration elements. - */ - private Map<String, IValidatorGroupListener[]> _resolved; - - private ValidatorGroupExtensionReader() { - init(); - } - - /** - * Answer the listeners with this group id. - * @param groupID - * @return an empty array there are no listeners for this group id. - */ - IValidatorGroupListener[] createListeners(String groupID) throws CoreException { - IValidatorGroupListener[] result = _resolved.get(groupID); - if (result != null)return result; - - List<IConfigurationElement> elements = _map.get(groupID); - if (elements == null){ - _resolved.put(groupID, new IValidatorGroupListener[0]); - String msg = NLS.bind("Configuration error, there is no validation listener group with id: {0}", groupID); //$NON-NLS-1$ - Status status = new Status(IStatus.ERROR, ValidationPlugin.PLUGIN_ID, msg); - throw new CoreException(status); - } - - List<IValidatorGroupListener> listeners = new ArrayList<IValidatorGroupListener>(elements.size()); - for (IConfigurationElement element : elements) { - IValidatorGroupListener listener; - try { - listener = (IValidatorGroupListener) element.createExecutableExtension(ExtensionConstants.Group.attClass); - listeners.add(listener); - } - catch (Exception e) { - ValidationPlugin.getPlugin().handleException(e); - listeners = new ArrayList<IValidatorGroupListener>(); - } - } - - result = listeners.toArray(new IValidatorGroupListener[listeners.size()]); - _resolved.put(groupID, result); - return result; - } - - /** - * Answer the extension point for the validatorGroups. - * - * @return null if there is a problem or no extensions. - */ - private IExtensionPoint getExtensionPoint() { - IExtensionRegistry registry = Platform.getExtensionRegistry(); - return registry.getExtensionPoint(ValidationPlugin.PLUGIN_ID, ExtensionConstants.group); - } - - private void init() { - _map = new HashMap<String, List<IConfigurationElement>>(4); - _resolved = new HashMap<String, IValidatorGroupListener[]>(4); - - IExtensionPoint extensionPoint = getExtensionPoint(); - if (extensionPoint != null) { - for (IExtension ext : extensionPoint.getExtensions()) { - for (IConfigurationElement group : ext.getConfigurationElements()) { - processGroupElement(group); - } - } - } - } - - private void processGroupElement(IConfigurationElement element) { - if (!ExtensionConstants.Group.elementGroup.equals(element.getName()))return; - - String id = element.getAttribute(ExtensionConstants.Group.attId); - if (id == null)throw new IllegalStateException("Configuration error, the " + //$NON-NLS-1$ - ExtensionConstants.Group.attId + " is required"); //$NON-NLS-1$ - // force the use of a qualified ID - if (id.indexOf(DOT) < 0) { - id = element.getContributor().getName() + DOT + id; - } - IConfigurationElement[] newElements = element.getChildren(ExtensionConstants.Group.elementListener); - if (newElements.length > 0) { - List<IConfigurationElement> elements = _map.get(id); - if (elements == null) { - elements = new ArrayList<IConfigurationElement>(); - _map.put(id, elements); - } - elements.addAll(Arrays.asList(newElements)); - } - } -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorMutable.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorMutable.java deleted file mode 100644 index d18b0c597..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/ValidatorMutable.java +++ /dev/null @@ -1,258 +0,0 @@ -package org.eclipse.wst.validation.internal; - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.Platform; -import org.eclipse.wst.validation.IMutableValidator; -import org.eclipse.wst.validation.MessageSeveritySetting; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.Validator.V1; -import org.eclipse.wst.validation.Validator.V2; -import org.eclipse.wst.validation.internal.model.FilterGroup; - -/** - * The mutable fields that a user can change through the preference or property page. - * @author karasiuk - * - */ -public final class ValidatorMutable implements IAdaptable, IMutableValidator { - - private boolean _build; - private boolean _manual; - private String _delegatingId; - - private int _changeCountGroups; - private int _changeCountMessages; - - private final String _name; - private final String _sourceId; - private final boolean _isV1; - private final boolean _isV2; - private final ValidatorMetaData _vmd; - private final String _id; - private final int _version; - - private FilterGroup[] _groups; - private final Map<String, MessageSeveritySetting> _messageSettings; - private final String _validatorClassname; - - private final boolean _origBuild; - private final boolean _origManual; - private final String _origDelegating; - - public ValidatorMutable(Validator validator) { - _name = validator.getName(); - _sourceId = validator.getSourceId(); - _manual = validator.isManualValidation(); - _build = validator.isBuildValidation(); - V2 v2 = validator.asV2Validator(); - _isV2 = v2 != null; - _delegatingId = validator.getDelegatingId(); - - V1 v1 = validator.asV1Validator(); - _isV1 = v1 != null; - _vmd = _isV1 ? v1.getVmd() : null; - _id = validator.getId(); - - _origBuild = _build; - _origDelegating = _delegatingId; - _origManual = _manual; - _version = validator.getVersion(); - _validatorClassname = validator.getValidatorClassname(); - _messageSettings = new HashMap<String, MessageSeveritySetting>(10); - for (Map.Entry<String, MessageSeveritySetting> me : validator.getMessageSettings().entrySet()){ - _messageSettings.put(me.getKey(), me.getValue().copy()); - } - - if (v2 != null){ - FilterGroup[] groups = v2.getGroups(); - _groups = new FilterGroup[groups.length]; - System.arraycopy(groups, 0, _groups, 0, groups.length); - } - } - - public ValidatorMutable(ValidatorMutable val) { - _build = val._build; - _delegatingId = val._delegatingId; - FilterGroup[] groups = val.getGroups(); - _groups = new FilterGroup[groups.length]; - System.arraycopy(groups, 0, _groups, 0, groups.length); - - _id = val._id; - _isV1 = val._isV1; - _isV2 = val._isV2; - _manual = val._manual; - _messageSettings = new HashMap<String, MessageSeveritySetting>(10); - for (Map.Entry<String, MessageSeveritySetting> me : val.getMessageSettings().entrySet()){ - _messageSettings.put(me.getKey(), me.getValue().copy()); - } - - _name = val._name; - _origBuild = val._origBuild; - _origDelegating = val._origDelegating; - _origManual = val._origManual; - _sourceId = val._sourceId; - _validatorClassname = val._validatorClassname; - _version = val._version; - _vmd = val._vmd; - } - - public void setBuildValidation(boolean build) { - _build = build; - } - - public void setManualValidation(boolean manual) { - _manual = manual; - } - - public String getName() { - return _name; - } - - public boolean isManualValidation() { - return _manual; - } - - public boolean isBuildValidation() { - return _build; - } - - public boolean isV2Validator() { - return _isV2; - } - - public String getDelegatingId() { - return _delegatingId; - } - - /** - * The caller of this method must not change the ValidatorMetaData. - */ - public ValidatorMetaData getVmd() { - return _vmd; - } - - public boolean isV1Validator() { - return _isV1; - } - - public String getId() { - return _id; - } - - /** - * Answer true if any of your settings have changed. - */ - public boolean isChanged() { - if (hasGlobalChanges())return true; - if (_changeCountGroups > 0 || _changeCountMessages > 0)return true; - return false; - } - - public boolean hasGlobalChanges() { - if (_origBuild != _build)return true; - if (_origManual != _manual)return true; - if (!Misc.same(_origDelegating, _delegatingId))return true; - return false; - } - - public int getVersion() { - return _version; - } - - public void replaceFilterGroup(FilterGroup existing, FilterGroup merged) { - int i = find(existing); - if (i == -1)add(merged); // this should never happen - else { - _groups[i] = merged; - bumpChangeCountGroups(); - } - } - - public void remove(FilterGroup group) { - int i = find(group); - if (i == -1)return; - - FilterGroup[] groups = new FilterGroup[_groups.length-1]; - if (i > 0)System.arraycopy(_groups, 0, groups, 0, i); - if (i < groups.length)System.arraycopy(_groups, i+1, groups, i, groups.length-i); - _groups = groups; - bumpChangeCountGroups(); - } - - private int find(FilterGroup group) { - for (int i=0; i<_groups.length; i++)if (group == _groups[i])return i; - return -1; - } - - public void add(FilterGroup fg) { - assert fg != null; - FilterGroup[] groups = new FilterGroup[_groups.length+1]; - System.arraycopy(_groups, 0, groups, 0, _groups.length); - groups[_groups.length] = fg; - _groups = groups; - bumpChangeCountGroups(); - } - - private void bumpChangeCountGroups(){ - _changeCountGroups++; - } - - public int getChangeCountGroups() { - return _changeCountGroups; - } - - public FilterGroup[] getGroups(){ - return _groups; - } - - public void setDelegatingId(String id) { - _delegatingId = id; - } - - public Map<String, MessageSeveritySetting> getMessageSettings() { - return _messageSettings; - } - - public void bumpChangeCountMessages(){ - _changeCountMessages++; - } - - public String getValidatorClassname() { - return _validatorClassname; - } - - @SuppressWarnings("unchecked") - public Object getAdapter(Class adapter) { - return Platform.getAdapterManager().getAdapter(this, adapter); - } - - public boolean sameConfig(Validator validator) { - if (validator == null)return false; - return hashCodeForConfig() == validator.hashCodeForConfig(); - } - - private int hashCodeForConfig() { - int h = 0; - if (_build)h += 101; - if (_delegatingId != null)h += _delegatingId.hashCode(); - if (_manual)h += 201; - if (_messageSettings != null){ - for (MessageSeveritySetting ms : _messageSettings.values())h += ms.hashCode(); - } - if (_sourceId != null)h += _sourceId.hashCode(); - h += _version; - if (_id != null)h += _id.hashCode(); - for (FilterGroup fg : _groups)h += fg.hashCodeForConfig(); - return h; - } - - @Override - public String toString() { - return _name; - } - - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterGroup.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterGroup.java deleted file mode 100644 index 6d20dd5a8..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterGroup.java +++ /dev/null @@ -1,253 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 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.wst.validation.internal.model; - -import java.util.LinkedList; -import java.util.List; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.Platform; -import org.eclipse.wst.validation.internal.ContentTypeWrapper; -import org.eclipse.wst.validation.internal.Deserializer; -import org.eclipse.wst.validation.internal.ExtensionConstants; -import org.eclipse.wst.validation.internal.Serializer; -import org.eclipse.wst.validation.internal.ValMessages; - -/** - * An immutable group of filter rules. - * @author karasiuk - * - */ -public abstract class FilterGroup implements IAdaptable { - - private final FilterRule[] _rules; - - /** The version number of the serialization (in case we ever need to change this) */ - private static final int SerializationVersion = 1; - - /** - * Answer a filter group based on the type of the group. - * - * @param name either "include" or "exclude" - * - * @return null if the name parameter isn't correct. - */ - public static FilterGroup create(String name, FilterRule[] rules) { - if (ExtensionConstants.include.equals(name))return new FilterIncludeGroup(rules); - if (ExtensionConstants.exclude.equals(name))return new FilterExcludeGroup(rules); - return null; - } - - /** - * Answer a filter group from a deserializer. - * @param des - * - * @see FilterGroup#save(Serializer) - */ - public static FilterGroup create(Deserializer des){ - des.getInt(); // get the version - String type = des.getString(); - - int numberRules = des.getInt(); - List<FilterRule> list = new LinkedList<FilterRule>(); - for (int i=0; i<numberRules; i++)list.add(FilterRule.create(des)); - FilterRule[] rules = new FilterRule[list.size()]; - list.toArray(rules); - - return create(type, rules); - } - - /** - * Answer a new filter group. - * - * @param exclude if true an exclusion group is returned, otherwise an inclusion group is returned. - */ - public static FilterGroup create(boolean exclude, FilterRule[] rules){ - if (exclude) return new FilterExcludeGroup(rules); - return new FilterIncludeGroup(rules); - } - - /** - * Answer true if this is a supported type of group. - * @param name Type of group that is being tested. - * @return - */ - public static boolean isKnownName(String name) { - if (ExtensionConstants.include.equals(name))return true; - if (ExtensionConstants.exclude.equals(name))return true; - return false; - } - - - private FilterGroup(FilterRule[] rules){ - _rules = rules; - } - - /** - * The rules in the group. - */ - public final FilterRule[] getRules(){ - FilterRule[] rules = new FilterRule[_rules.length]; - System.arraycopy(_rules, 0, rules, 0, _rules.length); - return rules; - } - - /** - * Answer the internal type of group, e.g. "include" or "exclude". - */ - public abstract String getType(); - - /** Answer the type as a type that can be displayed to a user, that is it has been localized. */ - public abstract String getDisplayableType(); - - @SuppressWarnings("unchecked") - public Object getAdapter(Class adapter) { - return Platform.getAdapterManager().getAdapter(this, adapter); - } - - public static final class FilterIncludeGroup extends FilterGroup { - - private FilterIncludeGroup(FilterRule[] rules){ - super(rules); - } - - public String getType() { - return ExtensionConstants.include; - } - - public String getDisplayableType() { - return ValMessages.GroupInclude; - } - - public boolean isInclude() { - return true; - } - - } - - - public static final class FilterExcludeGroup extends FilterGroup { - - private FilterExcludeGroup(FilterRule[] rules){ - super(rules); - } - public String getType() { - return ExtensionConstants.exclude; - } - - public String getDisplayableType() { - return ValMessages.GroupExclude; - } - - public boolean isExclude() { - return true; - } - } - - /** - * Save your settings into the serializer. - * @param ser - */ - public void save(Serializer ser){ - ser.put(SerializationVersion); - ser.put(getType()); - ser.put(_rules.length); - for (FilterRule rule : _rules)rule.save(ser); - } - - /** - * Answer whether or not we should validate the resource based on the filters in this group. - * - * @param project the project that is being validated. - * @param resource the resource that is being validated. This can be null, in which case - * only the project level checks are performed. - */ - public boolean shouldValidate(IProject project, IResource resource, ContentTypeWrapper contentTypeWrapper) { - boolean exclude = isExclude(); - boolean include = isInclude(); - int count = 0; - for (FilterRule rule : _rules){ - if (resource != null){ - Boolean match = rule.matchesResource(resource, contentTypeWrapper); - if (match != null)count++; - if (exclude && match != null && match)return false; - if (include && match != null && match)return true; - } - - Boolean match = rule.matchesProject(project); - if (match != null)count++; - if (exclude && match != null && match)return false; - if (include && match != null && match)return true; - } - if (exclude)return true; - if (count == 0)return true; - return false; - } - - /** - * Answer true if this is an inclusion filter, that is at least one of the rules must - * match in order to validate the resource. - */ - public boolean isInclude() { - return false; - } - - /** - * Answer true if this is an exclusion filter, that is if any of the rules match the - * resource is not validated. - */ - public boolean isExclude() { - return false; - } - - public int hashCodeForConfig() { - int h = 0; - if (isExclude())h += 13; - for (FilterRule fr : _rules)h += fr.hashCodeForConfig(); - return h; - } - - /** - * Create a new group by adding a rule to an existing group. - * @param baseGroup The group that holds the existing rules. - * @param rule The new rule that is being added - * @return - */ - public static FilterGroup addRule(FilterGroup baseGroup, FilterRule rule) { - List<FilterRule> list = new LinkedList<FilterRule>(); - for (FilterRule r : baseGroup._rules)list.add(r); - list.add(rule); - - FilterRule[] rules = new FilterRule[list.size()]; - list.toArray(rules); - return FilterGroup.create(baseGroup.isExclude(), rules); - } - - /** - * Create a new group by removing a rule from an existing group. - * @param baseGroup The group that holds the existing rules. - * @param rule The rule that is being removed - * @return - */ - public static FilterGroup removeRule(FilterGroup baseGroup, FilterRule rule) { - List<FilterRule> list = new LinkedList<FilterRule>(); - for (FilterRule r : baseGroup._rules){ - if (!r.equals(rule))list.add(r); - } - - FilterRule[] rules = new FilterRule[list.size()]; - list.toArray(rules); - return FilterGroup.create(baseGroup.isExclude(), rules); - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterRule.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterRule.java deleted file mode 100644 index e50df6155..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/FilterRule.java +++ /dev/null @@ -1,535 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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.wst.validation.internal.model; - -import java.util.regex.Pattern; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.common.project.facet.core.FacetedProjectFramework; -import org.eclipse.wst.validation.internal.ContentTypeWrapper; -import org.eclipse.wst.validation.internal.Deserializer; -import org.eclipse.wst.validation.internal.ExtensionConstants; -import org.eclipse.wst.validation.internal.Serializer; -import org.eclipse.wst.validation.internal.Tracing; -import org.eclipse.wst.validation.internal.ValMessages; -import org.eclipse.wst.validation.internal.plugin.ValidationPlugin; - -/** - * A rule that is used to filter out (or in) validation on a resource. - * The concrete classes are all immutable. - * @author karasiuk - * - */ -public abstract class FilterRule implements IAdaptable { - - protected final String _pattern; - - protected static final String PortableFileDelim = "/"; //$NON-NLS-1$ - - /** - * Create a rule based on a configuration element. - * - * @param rule - * The configuration element, see the extension point for details. - * @return null if there is a problem. - */ - public static FilterRule create(IConfigurationElement rule){ - String name = rule.getName(); - if (ExtensionConstants.Rule.fileext.equals(name))return new FileExt(rule); - if (ExtensionConstants.Rule.projectNature.equals(name))return new ProjectNature(rule); - if (ExtensionConstants.Rule.file.equals(name))return File.createFile(rule); - if (ExtensionConstants.Rule.contentType.equals(name))return ContentType.createContentType(rule); - if (ExtensionConstants.Rule.facet.equals(name))return new Facet(rule); - if (ExtensionConstants.Rule.pattern.equals(name))return FilePattern.createFilePattern(rule); - return null; - } - - static FilterRule create(Deserializer des) { - String type = des.getString(); - if (ExtensionConstants.Rule.fileext.equals(type)){ - String pattern = des.getString(); - boolean caseSensitive = des.getBoolean(); - return new FileExt(pattern, caseSensitive); - } - - if (ExtensionConstants.Rule.projectNature.equals(type)){ - String pattern = des.getString(); - return new ProjectNature(pattern); - } - - if (ExtensionConstants.Rule.file.equals(type)){ - String pattern = des.getString(); - boolean caseSensitive = des.getBoolean(); - int fileType = des.getInt(); - return new File(pattern, caseSensitive, fileType); - } - - if (ExtensionConstants.Rule.contentType.equals(type)){ - String pattern = des.getString(); - boolean exactMatch = des.getBoolean(); - return new ContentType(pattern, exactMatch); - } - - if (ExtensionConstants.Rule.facet.equals(type)){ - String pattern = des.getString(); - return new Facet(pattern, null); - } - - if (ExtensionConstants.Rule.pattern.equals(type)){ - String pattern = des.getString(); - boolean caseSensitive = des.getBoolean(); - return new FilePattern(pattern, caseSensitive); - } - return null; - } - - - public static FilterRule createFile(String pattern, boolean caseSensitive, int type){ - return new File(pattern, caseSensitive, type); - } - - public static FilterRule createFileExt(String pattern, boolean caseSensitive){ - FileExt ext = new FileExt(pattern, caseSensitive); - return ext; - } - - public static FilterRule createFacet(String facetId){ - return new Facet(facetId, null); - } - - public static FilterRule createProject(String projectNature){ - return new ProjectNature(projectNature); - } - - public static FilterRule createContentType(String contentType, boolean exactMatch){ - return new ContentType(contentType, exactMatch); - } - - protected FilterRule(String pattern){ - _pattern = pattern; - } - - /** - * Answer true if the rule matches the resource, false if it doesn't, and - * null if the rule does not apply to resources. - * - * @param resource the resource that is being validated. - */ - public Boolean matchesResource(IResource resource, ContentTypeWrapper contentTypeWrapper){ - return null; - } - - /** - * Answer true if the rule matches the project, false if it doesn't, and null if the - * rule does not apply. - * - * @param project the project that is being validated. - */ - public Boolean matchesProject(IProject project){ - return null; - } - - public String toString() { - return getDisplayableType() + ": " + _pattern; //$NON-NLS-1$ - } - - /** Answer a name of the rule, that can be displayed to a user. */ - public String getName(){ - return toString(); - } - - public String getPattern(){ - return _pattern; - } - - /** Answer the type of rule. */ - public abstract String getType(); - - /** Answer a type that can be displayed to an end user. */ - public abstract String getDisplayableType(); - - public static boolean asBoolean(String value, boolean aDefault){ - if (value == null)return aDefault; - if (value.equals(ExtensionConstants.True))return true; - if (value.equals(ExtensionConstants.False))return false; - return aDefault; - } - - @SuppressWarnings("unchecked") - public Object getAdapter(Class adapter) { - return Platform.getAdapterManager().getAdapter(this, adapter); - } - - public static abstract class FilterRuleCaseSensitive extends FilterRule { - - public FilterRuleCaseSensitive(String pattern, boolean caseSensitive) { - super(pattern); - _caseSensitive = caseSensitive; - } - - private final boolean _caseSensitive; - - @Override - public int hashCodeForConfig() { - int h = super.hashCodeForConfig(); - if (_caseSensitive)h += 401; - return h; - } - - @Override - public void save(Serializer ser) { - super.save(ser); - ser.put(_caseSensitive); - } - - public boolean isCaseSensitive() { - return _caseSensitive; - } - - } - - public static final class ProjectNature extends FilterRule { - - private ProjectNature(IConfigurationElement rule) { - super(rule.getAttribute(ExtensionConstants.RuleAttrib.id)); - - } - - public ProjectNature(String projectNature) { - super(projectNature); - } - - public String getDisplayableType() { - return ValMessages.RuleProjectNature; - } - - public String getType() { - return ExtensionConstants.Rule.projectNature; - } - - public Boolean matchesProject(IProject project) { - try { - return project.hasNature(_pattern); - } - catch (CoreException e){ - } - return Boolean.FALSE; - } - - } - - public static final class FileExt extends FilterRuleCaseSensitive { - - private FileExt(IConfigurationElement rule){ - super(rule.getAttribute(ExtensionConstants.RuleAttrib.ext), - asBoolean(rule.getAttribute(ExtensionConstants.RuleAttrib.caseSensitive), false)); - } - - private FileExt(String pattern, boolean caseSensitive) { - super(pattern, caseSensitive); - } - - public String getType() { - return ExtensionConstants.Rule.fileext; - } - - public String getDisplayableType() { - return ValMessages.RuleFileExt; - } - - public String getName() { - return toString(); - } - - public String toString() { - if (isCaseSensitive())return NLS.bind(ValMessages.FileExtWithCase, getDisplayableType(), _pattern); - return NLS.bind(ValMessages.FileExtWithoutCase, getDisplayableType(), _pattern); - } - - public Boolean matchesResource(IResource resource, ContentTypeWrapper contentTypeWrapper) { - String ext = resource.getFileExtension(); - if (isCaseSensitive())return _pattern.equals(ext); - return _pattern.equalsIgnoreCase(ext); - } - } - - /** - * A rule that is used to filter based on file or folder names. - * @author karasiuk - * - */ - public static final class File extends FilterRuleCaseSensitive { - - private final String _patternAsLowercase; - - /** One of the FileTypeXX constants. */ - private final int _type; - - public static final int FileTypeFile = 1; - public static final int FileTypeFolder = 2; - public static final int FileTypeFull = 3; - - private static File createFile(IConfigurationElement rule){ - String pattern = rule.getAttribute(ExtensionConstants.RuleAttrib.name); - if (pattern == null)throw new IllegalStateException(ValMessages.ErrPatternAttrib); - String type = rule.getAttribute(ExtensionConstants.RuleAttrib.fileType); - if (type == null)throw new IllegalStateException(ValMessages.ErrTypeReq); - - int myType = -1; - if (ExtensionConstants.FileType.file.equals(type))myType = FileTypeFile; - else if (ExtensionConstants.FileType.folder.equals(type)){ - myType = FileTypeFolder; - if (!pattern.endsWith(PortableFileDelim))pattern += PortableFileDelim; - } - else if (ExtensionConstants.FileType.full.equals(type))myType = FileTypeFull; - else { - Object[] parms = {type, ExtensionConstants.FileType.file, ExtensionConstants.FileType.folder, - ExtensionConstants.FileType.full}; - throw new IllegalStateException(NLS.bind(ValMessages.ErrType, parms)); - } - boolean caseSensitive = asBoolean(rule.getAttribute(ExtensionConstants.RuleAttrib.caseSensitive), false); - return new File(pattern, caseSensitive, myType); - } - - private File(String pattern, boolean caseSensitive, int type){ - super(pattern, caseSensitive); - _type = type; - _patternAsLowercase = pattern == null ? null : pattern.toLowerCase(); - } - - public String getType() { - return ExtensionConstants.Rule.file; - } - - public String getDisplayableType() { - if (_type == FileTypeFolder)return ValMessages.RuleFolder; - if (_type == FileTypeFull)return ValMessages.RuleFull; - return ValMessages.RuleFile; - } - - public void setData(IConfigurationElement rule) { - } - - public String toString() { - if (isCaseSensitive())return NLS.bind(ValMessages.FileExtWithCase, getDisplayableType(), _pattern); - return NLS.bind(ValMessages.FileExtWithoutCase, getDisplayableType(), _pattern); - } - - public Boolean matchesResource(IResource resource, ContentTypeWrapper contentTypeWrapper) { - String name = null; - switch (_type){ - case FileTypeFile: - name = resource.getName(); - break; - - case FileTypeFolder: - name = resource.getProjectRelativePath().removeLastSegments(1).toString() + PortableFileDelim; - break; - - case FileTypeFull: - name = resource.getProjectRelativePath().toPortableString(); - break; - } - - if (name == null)return Boolean.FALSE; - if (isCaseSensitive())return name.startsWith(_pattern); - return name.toLowerCase().startsWith(_patternAsLowercase); - } - - @Override - public void save(Serializer ser) { - super.save(ser); - ser.put(_type); - } - - } - - public static final class Facet extends FilterRule { - - private final String _versionExpression; - - private Facet(IConfigurationElement rule){ - super(rule.getAttribute(ExtensionConstants.RuleAttrib.id)); - _versionExpression = rule.getAttribute(ExtensionConstants.RuleAttrib.version); - - } - - public Facet(String facetId, String versionExpression) { - super(facetId); - _versionExpression = versionExpression; - } - - public String getType() { - return ExtensionConstants.Rule.facet; - } - - public String getDisplayableType() { - return ValMessages.RuleFacet; - } - - @Override - public Boolean matchesProject(IProject project) { - try { - if (_versionExpression == null)return FacetedProjectFramework.hasProjectFacet(project, _pattern); - return FacetedProjectFramework.hasProjectFacet(project, _pattern, _versionExpression); - } - catch (CoreException e){ - if (Tracing.isLogging())ValidationPlugin.getPlugin().handleException(e); - } - return Boolean.FALSE; - } - - @Override - public String toString() { - StringBuffer b = new StringBuffer(200); - b.append(getDisplayableType()); - b.append(": "); //$NON-NLS-1$ - b.append(_pattern); - - if (_versionExpression != null){ - b.append(" ("); //$NON-NLS-1$ - b.append(_versionExpression); - b.append(")"); //$NON-NLS-1$ - } - return b.toString(); - } - - } - - public static final class ContentType extends FilterRule { - - private final IContentType _type; - private final boolean _exactMatch; - - private ContentType(String pattern, boolean exactMatch){ - super(pattern); - _type = Platform.getContentTypeManager().getContentType(pattern); - _exactMatch = exactMatch; - } - - private static ContentType createContentType(IConfigurationElement rule){ - String pattern = rule.getAttribute(ExtensionConstants.RuleAttrib.id); - boolean exactMatch = true; - String exact = rule.getAttribute(ExtensionConstants.RuleAttrib.exactMatch); - if (ExtensionConstants.False.equals(exact)) exactMatch = false; - - return new ContentType(pattern, exactMatch); - } - - public String getType() { - return ExtensionConstants.Rule.contentType; - } - - @Override - public int hashCodeForConfig() { - int h = super.hashCodeForConfig(); - if (_exactMatch)h += 301; - return h; - } - - public String getDisplayableType() { - return ValMessages.RuleContentType; - } - - @Override - public void save(Serializer ser) { - super.save(ser); - ser.put(_exactMatch); - } - - public void setData(IConfigurationElement rule) { - } - - public Boolean matchesResource(IResource resource, ContentTypeWrapper contentTypeWrapper) { - if (_type == null)return Boolean.FALSE; - if (resource instanceof IFile) { - IFile file = (IFile) resource; - IContentType ct = contentTypeWrapper.getContentType(file); - if (ct == null)return Boolean.FALSE; - boolean match = false; - if (_exactMatch)match = ct.getId().equals(_type.getId()); - else match = ct.isKindOf(_type); - - if (match && Tracing.isTraceMatches()) - Tracing.log("FilterRule-01: ", toString() + " has matched " + resource); //$NON-NLS-1$ //$NON-NLS-2$ - return match; - } - return Boolean.FALSE; - } - - @Override - public String toString() { - if (_exactMatch)return NLS.bind(ValMessages.ContentTypeExact, getDisplayableType(), _pattern); - return NLS.bind(ValMessages.ContentTypeNotExact, getDisplayableType(), _pattern); - } - - } - - public static final class FilePattern extends FilterRuleCaseSensitive { - - private final Pattern _compiledPattern; - - private static FilePattern createFilePattern(IConfigurationElement rule){ - String pattern = rule.getAttribute(ExtensionConstants.RuleAttrib.regex); - boolean caseSensitive = asBoolean(rule.getAttribute(ExtensionConstants.RuleAttrib.caseSensitive), false); - return new FilePattern(pattern, caseSensitive); - } - - private FilePattern(String pattern, boolean caseSensitive){ - super(pattern, caseSensitive); - int flags = 0; - if (caseSensitive)flags = Pattern.CASE_INSENSITIVE; - Pattern compiledPattern = Pattern.compile(pattern, flags); - _compiledPattern = compiledPattern; - } - - @Override - public String getDisplayableType() { - return ValMessages.RulePattern; - } - - @Override - public String getType() { - return ExtensionConstants.Rule.pattern; - } - - @Override - public Boolean matchesResource(IResource resource, ContentTypeWrapper wrapper) { - String name = PortableFileDelim + resource.getProjectRelativePath().toPortableString(); - if (name == null)return Boolean.FALSE; - return _compiledPattern.matcher(name).matches(); - } - } - - /** - * Save your settings into the serializer. - * @param ser - */ - public void save(Serializer ser) { - ser.put(getType()); - ser.put(getPattern()); - } - - public int hashCodeForConfig() { - int h = getType().hashCode(); - if (_pattern != null)h += _pattern.hashCode(); - return h; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferences.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferences.java deleted file mode 100644 index 2989c2c43..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferences.java +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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.wst.validation.internal.model; - -/** - * This class represents the global Preferences as set on the Validation Preferences page. It doesn't - * hold any of the individual validator settings, just the global check boxes. It is an immutable object. - */ -public final class GlobalPreferences { - - /** false - Default setting for the should all the validation be suspended setting. */ - public static final boolean DefaultSuspend = false; - - /** false - Default setting for the auto save setting. */ - public static final boolean DefaultAutoSave = false; - - /** false - Default setting for the confirm dialog setting. */ - public static final boolean DefaultConfirm = true; - - /** false - Default setting for letting projects override the global settings. */ - public static final boolean DefaultOverride = true; - - /** 2 - The version of the framework meta data, if an explicit version isn't found. */ - public static final int DefaultFrameworkVersion = 2; - - /** Bit masks for what has changed. */ - public final static int ConfirmDialogMask = 1; - public final static int DisableAllValidationMask = 2; - public final static int OverrideMask = 4; - public final static int SaveAutomaticallyMask = 8; - public final static int StateTimeStampMask = 16; - public final static int VersionMask = 32; - - /** - * The changes that could affect what gets validated. - */ - public final static int BuildChangeMask = DisableAllValidationMask | OverrideMask; - - - private final boolean _confirmDialog; - private final boolean _disableAllValidation; - private final boolean _override; - private final boolean _saveAutomatically; - - /** The plug-in state time stamp. */ - private final long _stateTimeStamp; - - /** The incoming version of the framework. This is used to determine if a migration is needed.*/ - private final int _version; - - /** - * The only valid way to get the global preferences is through the ValManager. - * - * @see org.eclipse.wst.validation.internal.ValManager#getGlobalPreferences() - */ - public GlobalPreferences(GlobalPreferencesValues gp) { - _confirmDialog = gp.confirmDialog; - _disableAllValidation = gp.disableAllValidation; - _override = gp.override; - _saveAutomatically = gp.saveAutomatically; - _stateTimeStamp = gp.stateTimeStamp; - _version = gp.version; - } - - /** - * Answer a copy of the values. - * @return - */ - public GlobalPreferencesValues asValues(){ - GlobalPreferencesValues gp = new GlobalPreferencesValues(); - gp.confirmDialog = _confirmDialog; - gp.disableAllValidation = _disableAllValidation; - gp.override = _override; - gp.saveAutomatically = _saveAutomatically; - gp.stateTimeStamp = _stateTimeStamp; - gp.version = _version; - return gp; - } - - public boolean getSaveAutomatically() { - return _saveAutomatically; - } - - - /** - * Answer if all validation has been disabled. - */ - public boolean getDisableAllValidation() { - return _disableAllValidation; - } - - public boolean getConfirmDialog() { - return _confirmDialog; - } - - public long getStateTimeStamp() { - return _stateTimeStamp; - } - - /** Answer whether or not projects are allowed to override the global preferences. */ - public boolean getOverride() { - return _override; - } - - public int getVersion() { - return _version; - } - - /** - * Compare yourself to the other global preferences and answer a bitmask with the differences. - * @param gp - * @return bit mask of the changes. See the xxxMask constants for the values of the bits. A zero means that they are the same. - */ - public int compare(GlobalPreferences gp) { - int changes = 0; - if (_confirmDialog != gp.getConfirmDialog())changes |= ConfirmDialogMask; - if (_disableAllValidation != gp.getDisableAllValidation())changes |= DisableAllValidationMask; - if (_override != gp.getOverride())changes |= OverrideMask; - if (_saveAutomatically != gp.getSaveAutomatically())changes |= SaveAutomaticallyMask; - if (_stateTimeStamp != gp.getStateTimeStamp())changes |= StateTimeStampMask; - if (_version != gp.getVersion())changes |= VersionMask; - return changes; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferencesValues.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferencesValues.java deleted file mode 100644 index cdf8345f7..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/GlobalPreferencesValues.java +++ /dev/null @@ -1,35 +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.wst.validation.internal.model; - -/** - * A mutable object that is used to initialize a GlobalPreference. - * @author karasiuk - * - */ -public class GlobalPreferencesValues { - public boolean disableAllValidation = GlobalPreferences.DefaultSuspend; - public boolean saveAutomatically = GlobalPreferences.DefaultAutoSave; - public boolean confirmDialog = GlobalPreferences.DefaultConfirm; - public boolean override = GlobalPreferences.DefaultOverride; - - /** The plug-in state time stamp. */ - public long stateTimeStamp; - - /** The incoming version of the framework. This is used to determine if a migration is needed.*/ - public int version; - - public GlobalPreferencesValues(){ - - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/IValidatorVisitor.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/IValidatorVisitor.java deleted file mode 100644 index 8c747362b..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/IValidatorVisitor.java +++ /dev/null @@ -1,46 +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.wst.validation.internal.model; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.wst.validation.Validator; -import org.eclipse.wst.validation.internal.ValOperation; -import org.eclipse.wst.validation.internal.ValType; - -/** - * This interface is implemented by objects that visit enabled validators. - * <p> - * Usage: - * <pre> - * class Visitor implements IValidatorVisitor { - * public void visit(Validator validator, IProgressMonitor monitor) { - * // your code here - * } - * } - * ValidatorManager vm = ValidatorManager.getDefault(); - * vm.accept(new Visitor(), ...); - * </pre> - * </p> - * <p> - * Clients may implement this interface. - * </p> - */ -public interface IValidatorVisitor { - - /** - * Visits the given validator. - * @param validator - */ - void visit(Validator validator, IProject project, ValType valType, - ValOperation operation, IProgressMonitor monitor); - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ProjectPreferences.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ProjectPreferences.java deleted file mode 100644 index dd26addad..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ProjectPreferences.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007, 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.wst.validation.internal.model; - -import org.eclipse.core.resources.IProject; -import org.eclipse.wst.validation.Validator; - -/** - * Validation preferences for a particular project. - * @author karasiuk - * - */ -public final class ProjectPreferences { - /* - * Before this object can be considered immutable, the mutable validators need to be addressed. - */ - /** false - Default setting for the "should all the validation be suspended" setting. */ - public static final boolean DefaultSuspend = false; - - /** false - Default setting for letting projects override the global settings. */ - public static final boolean DefaultOverride = false; - - private final IProject _project; - - private final boolean _override; - private final boolean _suspend; - - private final Validator[] _validators; - - public ProjectPreferences(IProject project){ - _project = project; - _override = DefaultOverride; - _suspend = DefaultSuspend; - _validators = new Validator[0]; - } - - public ProjectPreferences(IProject project, boolean override, boolean suspend, Validator[] validators){ - _project = project; - _override = override; - _suspend = suspend; - _validators = validators; - } - - public boolean getOverride() { - return _override; - } - public boolean getSuspend() { - return _suspend; - } - - /** - * Answer the validators that have been registered for this project. - * @return an empty array if there are no validators. - */ - public Validator[] getValidators() { - return _validators; - } - - public IProject getProject() { - return _project; - } - -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ValidatorHelper.java b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ValidatorHelper.java deleted file mode 100644 index 288f226bf..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/model/ValidatorHelper.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 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.wst.validation.internal.model; - -import org.eclipse.wst.validation.internal.ValidatorMutable; - -/** - * Implement some common validator methods, that don't need to be part of the API. - * - * @author karasiuk - * - */ -public final class ValidatorHelper { - - /** - * Answer true if this validator already has an exclude filter. - */ - public static boolean hasExcludeGroup(ValidatorMutable v){ - for (FilterGroup group : v.getGroups())if (group.isExclude())return true; - return false; - } -} diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/package.html b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/package.html deleted file mode 100644 index 4b88f6be8..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/internal/package.html +++ /dev/null @@ -1,10 +0,0 @@ -<html> -<body> -<h1>Validation Framework</h1> -<h3>Build Based Validation</h3> -The main class for build based validation is the -<a href="ValBuilderJob.html">ValBuilderJob</a>. This gets triggered as part of the -build mechanism. It reacts to resource change events, and from that determines what needs to be -validated. -</body> -</html> diff --git a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/package.html b/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/package.html deleted file mode 100644 index 8c3c426d5..000000000 --- a/plugins/org.eclipse.wst.validation/vf2/org/eclipse/wst/validation/package.html +++ /dev/null @@ -1,52 +0,0 @@ -<html> -<head> -<title>Validation Framework</title> -</head> -<body> -<p>A framework for calling validators that are build based.</p> -<p>Also see <a href="doc-files/faq.html">Frequently Asked Questions</a></p> -<p> -There are two main types of validation, <b>build based</b> and -<b>as you type</b>. This framework supports build based -validation. If auto build is turned on then the validators are called -when the user saves their file. If auto build is not turned on then -the validators are called when the user starts a build.</p> -<p>This framework was added to WTP in version 3.0.</p> -<h3>Dependency Support</h3> -<p>Sometimes resources depend on other resources, to determine whether they are -valid or not. An example would be that an XML resource could depend on a DTD. If at some -point in the future the DTD changes, then the dependent XML resource should be -revalidated to ensure that it still meets the requirements of the changed DTD -file. In order to do this efficiently, there needs to be an association between -the DTD and all the resources that depend on it.<p>To be as efficient as possible, the validation framework allows -this dependency information to be returned as part of a -<a href="AbstractValidator.html#validate(org.eclipse.core.resources.IResource, int, ValidationState, org.eclipse.core.runtime.IProgressMonitor)"> -validate operation</a>. Since the validator needed to figure this out anyways, -why not pass this information back to the framework, so that it can be saved. -This saves the cost of having to parse the file at some later point in time -(when the file is probably sitting cold on disk). The fewer times that we need -to open, read and/or parse the same file, will improve the performance of the -product. -<p>In particular when the validate method returns, a -<a href="ValidationResult.html">ValidationResult</a> must be returned, inside of -this result, all your dependencies need to be specified with the -<a href="ValidationResult.html#setDependsOn(org.eclipse.core.resources.IResource[])"> -setDependsOn</a> method.<p>In addition to keeping the dependency information -up-to-date through the normal course of validation, direct access is also -provided to the dependency support through the -<a href="ValidationFramework.html#getDependencyIndex()">getDependencyIndex</a> -method. The <a href="IDependencyIndex.html">IDependencyIndex</a> allows you to -directly manipulate the dependency information for a validator. -<h3>Entry Points into the Validation Framework</h3> -<p>Here are some of the points where the platform calls into the framework:</p> -<ul> -<li><b>Builder</b> - ValidationBuilder</li> -<li><b>IFacetedProjectListener</b> - ValManager</li> -<li><b>IJobChangeListener</b> - ValidationOperation, ValidationOperation.ValidationLauncherJob</li> -<li><b>IProjectChangeListener</b> - ValManager</li> -<li><b>IPropertyChangeListener</b> - ValidationConfiguration, DisabledResourceManager</li> -<li><b>IResourceChangeListener</b> - EventManger</li> -<li><b>IValChangedListener</b> - ValManager, DisabledValidatorManager</li> -</ul> -</body> -</html> |