diff options
Diffstat (limited to 'bundles/org.eclipse.wst.jsdt.web.core/src')
54 files changed, 0 insertions, 12361 deletions
diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/Assert.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/Assert.java deleted file mode 100644 index df2d397226..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/Assert.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.jsdt.web.core.internal; - -/** - * <code>Assert</code> is useful for for embedding runtime sanity checks in - * code. The predicate methods all test a condition and throw some type of - * unchecked exception if the condition does not hold. - * <p> - * Assertion failure exceptions, like most runtime exceptions, are thrown when - * something is misbehaving. Assertion failures are invariably unspecified - * behavior; consequently, clients should never rely on these being thrown (and - * certainly should not being catching them specifically). - * </p> - */ -public final class Assert { - - /** - * <code>AssertionFailedException</code> is a runtime exception thrown by - * some of the methods in <code>Assert</code>. - * <p> - * This class is not declared public to prevent some misuses; programs that - * catch or otherwise depend on assertion failures are susceptible to - * unexpected breakage when assertions in the code are added or removed. - * </p> - */ - class AssertionFailedException extends RuntimeException { - /** - * Comment for <code>serialVersionUID</code> - */ - private static final long serialVersionUID = 1L; - - /** - * Constructs a new exception. - */ - public AssertionFailedException() { - super(); - } - - /** - * Constructs a new exception with the given message. - */ - public AssertionFailedException(String detail) { - super(detail); - } - } - - /** - * Asserts that an argument is legal. If the given boolean is not - * <code>true</code>, an <code>IllegalArgumentException</code> is - * thrown. The given message is included in that exception, to aid - * debugging. - * - * @param expression - * the outcode of the check - * @param message - * the message to include in the exception - * @return <code>true</code> if the check passes (does not return if the - * check fails) - * @exception IllegalArgumentException - * if the legality test failed - */ - public static boolean isLegal(boolean expression, String message) { - if (!expression) { - throw new IllegalArgumentException(message); - } - return expression; - } - - /** - * Asserts that the given object is not <code>null</code>. If this is not - * the case, some kind of unchecked exception is thrown. The given message - * is included in that exception, to aid debugging. - * - * @param object - * the value to test - * @param message - * the message to include in the exception - * @exception IllegalArgumentException - * if the object is <code>null</code> - */ - public static void isNotNull(Object object, String message) { - if (object == null) { - throw new Assert().new AssertionFailedException(message); - } - } - - /** - * Asserts that the given boolean is <code>true</code>. If this is not - * the case, some kind of unchecked exception is thrown. The given message - * is included in that exception, to aid debugging. - * - * @param expression - * the outcode of the check - * @param message - * the message to include in the exception - * @return <code>true</code> if the check passes (does not return if the - * check fails) - */ - public static boolean isTrue(boolean expression, String message) { - if (!expression) { - throw new Assert().new AssertionFailedException(message); - } - return expression; - } - - /* This class is not intended to be instantiated. */ - private Assert() { - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/JSPCoreMessages.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/JSPCoreMessages.java deleted file mode 100644 index fa63be8556..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/JSPCoreMessages.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005 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.jsdt.web.core.internal; - -import org.eclipse.osgi.util.NLS; - -/** - * Strings used by JSP Core - * - * @plannedfor 1.0 - */ -public class JSPCoreMessages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.wst.jsdt.web.core.internal.JSPCorePluginResources"; //$NON-NLS-1$ - - public static String JSP_Search; - public static String JSPBatchValidator_0; - public static String JSPDirectiveValidator_0; - public static String JSPDirectiveValidator_1; - public static String JSPDirectiveValidator_2; - public static String JSPDirectiveValidator_3; - public static String JSPDocumentLoader_1; - public static String JSPEL_Syntax; - public static String JSPEL_Token; - public static String JSPFContentPropertiesManager_Problems_Updating; - public static String JSPFContentPropertiesManager_Updating; - public static String JSPIndexManager_0; - public static String JSPIndexManager_2; - - /** - * @deprecated - */ - @Deprecated - public static String MESSAGE_JSP_VALIDATING_MESSAGE_UI_; - - static { - // initialize resource bundle - NLS.initializeMessages(JSPCoreMessages.BUNDLE_NAME, JSPCoreMessages.class); - } - - private JSPCoreMessages() { - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/JSPCorePlugin.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/JSPCorePlugin.java deleted file mode 100644 index 62adf84703..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/JSPCorePlugin.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal; - -import org.eclipse.core.runtime.Plugin; -import org.eclipse.wst.jsdt.web.core.internal.contentproperties.JSPFContentPropertiesManager; -import org.eclipse.wst.jsdt.web.core.internal.java.search.JSPIndexManager; -import org.osgi.framework.BundleContext; - -/** - * The main plugin class to be used in the desktop. - */ -public class JSPCorePlugin extends Plugin { - // The shared instance. - private static JSPCorePlugin plugin; - public static final String PLUGIN_ID = "org.eclipse.wst.jsdt.web"; - - /** - * Returns the shared instance. - * - * @deprecated - will be removed. Currently used to get "model preferences", - * but there are other, better ways. - */ - @Deprecated - public static JSPCorePlugin getDefault() { - return JSPCorePlugin.plugin; - } - - /** - * The constructor. - */ - public JSPCorePlugin() { - super(); - JSPCorePlugin.plugin = this; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.core.runtime.Plugin#start(org.osgi.framework.BundleContext) - */ - @Override - public void start(BundleContext context) throws Exception { - super.start(context); - - // JSPIndexManager depends on TaglibController, so TaglibController - // should be started first - - // listen for classpath changes - - JSPIndexManager.getInstance().initialize(); - - // listen for resource changes to update content properties keys - JSPFContentPropertiesManager.startup(); - - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext) - */ - @Override - public void stop(BundleContext context) throws Exception { - // stop listenning for resource changes to update content properties - // keys - JSPFContentPropertiesManager.shutdown(); - - // stop any indexing - JSPIndexManager.getInstance().shutdown(); - - super.stop(context); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/JSPCorePluginResources.properties b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/JSPCorePluginResources.properties deleted file mode 100644 index 9b58c0a836..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/JSPCorePluginResources.properties +++ /dev/null @@ -1,24 +0,0 @@ -############################################################################### -# Copyright (c) 2004 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 -############################################################################### -JSPIndexManager_0=Updating JSP Index -JSPIndexManager_2=JSP Indexer indexing {0} files -JSP_Search=JSP Search - -JSPDocumentLoader_1=Program Error: structured model had no structuredDocument -JSPEL_Syntax=EL Syntax Error -JSPEL_Token=Unable to analyse EL expression due to lexical analysis error -MESSAGE_JSP_VALIDATING_MESSAGE_UI_=JSP Validator validating {0} -JSPFContentPropertiesManager_Updating=Updating JSP Fragment Content Settings -JSPFContentPropertiesManager_Problems_Updating=Problem saving JSP Fragment Content Settings for {0} -JSPDirectiveValidator_0={0} is a reserved prefix. Try another -JSPDirectiveValidator_1=Cannot find the tag library descriptor for {0} -JSPDirectiveValidator_2=The prefix {0} is used more than once -JSPDirectiveValidator_3=A {0} value is required in this directive -JSPBatchValidator_0=Gathering files in {0} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/Logger.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/Logger.java deleted file mode 100644 index c7dd2f8c23..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/Logger.java +++ /dev/null @@ -1,158 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal; - -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.osgi.framework.Bundle; - -import com.ibm.icu.util.StringTokenizer; - -/** - * Small convenience class to log messages to plugin's log file and also, if - * desired, the console. This class should only be used by classes in this - * plugin. Other plugins should make their own copy, with appropriate ID. - */ -public class Logger { - public static final int ERROR = IStatus.ERROR; // 4 - - public static final int ERROR_DEBUG = 200 + Logger.ERROR; - - public static final int INFO = IStatus.INFO; // 1 - public static final int INFO_DEBUG = 200 + Logger.INFO; - public static final int OK = IStatus.OK; // 0 - public static final int OK_DEBUG = 200 + Logger.OK; - - private static final String PLUGIN_ID = "org.eclipse.wst.jsdt.web.core"; //$NON-NLS-1$ - private static final String TRACEFILTER_LOCATION = "/debug/tracefilter"; //$NON-NLS-1$ - public static final int WARNING = IStatus.WARNING; // 2 - public static final int WARNING_DEBUG = 200 + Logger.WARNING; - - /** - * Adds message to log. - * - * @param level - * severity level of the message (OK, INFO, WARNING, ERROR, - * OK_DEBUG, INFO_DEBUG, WARNING_DEBUG, ERROR_DEBUG) - * @param message - * text to add to the log - * @param exception - * exception thrown - */ - protected static void _log(int level, String message, Throwable exception) { - if (level == Logger.OK_DEBUG || level == Logger.INFO_DEBUG || level == Logger.WARNING_DEBUG || level == Logger.ERROR_DEBUG) { - if (!Logger.isDebugging()) { - return; - } - } - - int severity = IStatus.OK; - switch (level) { - case INFO_DEBUG: - case INFO: - severity = IStatus.INFO; - break; - case WARNING_DEBUG: - case WARNING: - severity = IStatus.WARNING; - break; - case ERROR_DEBUG: - case ERROR: - severity = IStatus.ERROR; - } - message = (message != null) ? message : "null"; //$NON-NLS-1$ - Status statusObj = new Status(severity, Logger.PLUGIN_ID, severity, message, exception); - Bundle bundle = Platform.getBundle(Logger.PLUGIN_ID); - if (bundle != null) { - Platform.getLog(bundle).log(statusObj); - } - } - - /** - * Prints message to log if category matches /debug/tracefilter option. - * - * @param message - * text to print - * @param category - * category of the message, to be compared with - * /debug/tracefilter - */ - protected static void _trace(String category, String message, Throwable exception) { - if (Logger.isTracing(category)) { - message = (message != null) ? message : "null"; //$NON-NLS-1$ - Status statusObj = new Status(IStatus.OK, Logger.PLUGIN_ID, IStatus.OK, message, exception); - Bundle bundle = Platform.getBundle(Logger.PLUGIN_ID); - if (bundle != null) { - Platform.getLog(bundle).log(statusObj); - } - } - } - - /** - * @return true if the platform is debugging - */ - public static boolean isDebugging() { - return Platform.inDebugMode(); - } - - /** - * Determines if currently tracing a category - * - * @param category - * @return true if tracing category, false otherwise - */ - public static boolean isTracing(String category) { - if (!Logger.isDebugging()) { - return false; - } - - String traceFilter = Platform.getDebugOption(Logger.PLUGIN_ID + Logger.TRACEFILTER_LOCATION); - if (traceFilter != null) { - StringTokenizer tokenizer = new StringTokenizer(traceFilter, ","); //$NON-NLS-1$ - while (tokenizer.hasMoreTokens()) { - String cat = tokenizer.nextToken().trim(); - if (category.equals(cat)) { - return true; - } - } - } - return false; - } - - public static void log(int level, String message) { - Logger._log(level, message, null); - } - - public static void log(int level, String message, Throwable exception) { - Logger._log(level, message, exception); - } - - public static void logException(String message, Throwable exception) { - Logger._log(Logger.ERROR, message, exception); - } - - public static void logException(Throwable exception) { - Logger._log(Logger.ERROR, exception.getMessage(), exception); - } - - public static void trace(String category, String message) { - Logger._trace(category, message, null); - } - - public static void traceException(String category, String message, Throwable exception) { - Logger._trace(category, message, exception); - } - - public static void traceException(String category, Throwable exception) { - Logger._trace(category, exception.getMessage(), exception); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contentproperties/JSPFContentProperties.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contentproperties/JSPFContentProperties.java deleted file mode 100644 index ce101e2ff7..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contentproperties/JSPFContentProperties.java +++ /dev/null @@ -1,215 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.web.core.internal.contentproperties; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.ProjectScope; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.wst.jsdt.web.core.internal.JSPCorePlugin; -import org.eclipse.wst.jsdt.web.core.internal.Logger; -import org.osgi.service.prefs.BackingStoreException; -import org.osgi.service.prefs.Preferences; - -/** - * Properties constants used by JSP Fragments. Clients should only read and - * modify the JSP Fragment properties programmatically using this class. - * - * @since 1.1 - */ -public class JSPFContentProperties { - /** - * A named key that controls the default content type for JSP Fragments - * <p> - * Value is of type <code>String</code>. - * </p> - * - * @since 1.1 - */ - public static final String JSPCONTENTTYPE = "jsp-content-type"; //$NON-NLS-1$ - static final String JSPCORE_ID = JSPCorePlugin.getDefault().getBundle().getSymbolicName(); - - /** - * A named key that controls the default language for JSP Fragments - * <p> - * Value is of type <code>String</code>. - * </p> - * - * @since 1.1 - */ - public static final String JSPLANGUAGE = "jsp-language"; //$NON-NLS-1$ - private static final String PROJECT_KEY = "<project>"; //$NON-NLS-1$ - /** - * Indicates if JSP fragments should be compiled/validated. JSP fragments - * will be validated when true. - * <p> - * Value is of type <code>String</code>. - * </p> - * - * @since 1.1 - */ - public static final String VALIDATE_FRAGMENTS = "validateFragments"; //$NON-NLS-1$ - - /** - * Generates a preference key based on resourcePath - * - * @param resourcePath - * the path the key will be based off of - * @return preference key based on resourcePath (basically the resourcePath - * without the filename); PROJECT_KEY if resourcePath is null - */ - static String getKeyFor(IPath resourcePath) { - String key = JSPFContentProperties.PROJECT_KEY; - if (resourcePath != null && resourcePath.segmentCount() > 1) { - key = resourcePath.removeFirstSegments(1).toString(); - } - return key; - } - - /** - * Get the preferences node associated with the given project scope and - * preference key (subNode) If create is true, the preference node will be - * created if one does not already exist - * - * @param project - * the project the preference node is under - * @param preferenceKey - * the subnode/category the preference node is located in - * @param create - * if true, a preference node will be created if one does not - * already exist - * @return Preferences associated with the given project scope and - * preference key. null if one could not be found and create is - * false - */ - static Preferences getPreferences(IProject project, String preferenceKey, boolean create) { - if (create) { - // create all nodes down to the one we are interested in - return new ProjectScope(project).getNode(JSPFContentProperties.JSPCORE_ID).node(preferenceKey); - } - // be careful looking up for our node so not to create any nodes as - // side effect - Preferences node = Platform.getPreferencesService().getRootNode().node(ProjectScope.SCOPE); - try { - // TODO once bug 90500 is fixed, should be as simple as this: - // String path = project.getName() + IPath.SEPARATOR + - // ResourcesPlugin.PI_RESOURCES + IPath.SEPARATOR + - // ENCODING_PREF_NODE; - // return node.nodeExists(path) ? node.node(path) : null; - // for now, take the long way - if (!node.nodeExists(project.getName())) { - return null; - } - node = node.node(project.getName()); - if (!node.nodeExists(JSPFContentProperties.JSPCORE_ID)) { - return null; - } - node = node.node(JSPFContentProperties.JSPCORE_ID); - if (!node.nodeExists(preferenceKey)) { - return null; - } - return node.node(preferenceKey); - } catch (BackingStoreException e) { - // nodeExists failed - Logger.log(Logger.WARNING_DEBUG, "Could not retrieve preference node", e); //$NON-NLS-1$ - } - return null; - } - - /** - * Returns the value for the given key in the given context. - * - * @param key - * The property key - * @param resource - * The current context or <code>null</code> if no context is - * available and the workspace setting should be taken. Note that - * passing <code>null</code> should be avoided. - * @param recurse - * whether the parent should be queried till property is found - * @return Returns the current value for the key. - * @since 1.1 - */ - public static String getProperty(String key, IResource resource, boolean recurse) { - String val = null; - if (resource != null) { - IProject project = resource.getProject(); - if (project != null) { - Preferences preferences = JSPFContentProperties.getPreferences(project, key, false); - if (preferences != null) { - val = JSPFContentProperties.internalGetProperty(resource, recurse, preferences); - } - } - } - // no preferences found - for performance reasons, - // short-circuit - // lookup by falling back to workspace's default - // setting - if (val == null && recurse) { - val = JSPFContentProperties.getWorkbenchPreference(key); - } - return val; - } - - private static String getWorkbenchPreference(String key) { - return Platform.getPreferencesService().getString(JSPFContentProperties.JSPCORE_ID, key, null, null); - } - - private static String internalGetProperty(IResource resource, boolean recurse, Preferences preferences) { - String value = preferences.get(JSPFContentProperties.getKeyFor(resource.getFullPath()), null); - if (value == null && resource != resource.getProject() && recurse) { - value = preferences.get(JSPFContentProperties.getKeyFor(null), null); - } - - return value; - } - - /** - * Sets the value for the given key in the given context. - * - * @param key - * The property key - * @param resource - * The current context. Note context cannot be <code>null</code>. - * @param value - * The value to set for the key. If value is <code>null</code> - * the key is removed from properties. - * @since 1.1 - */ - public static void setProperty(String key, IResource resource, String value) throws CoreException { - if (resource != null) { - IProject project = resource.getProject(); - if (project != null) { - Preferences preferences = JSPFContentProperties.getPreferences(project, key, true); - if (value == null || value.trim().length() == 0) { - preferences.remove(JSPFContentProperties.getKeyFor(resource.getFullPath())); - } else { - preferences.put(JSPFContentProperties.getKeyFor(resource.getFullPath()), value); - } - try { - // save changes - preferences.flush(); - } catch (BackingStoreException e) { - throw new CoreException(new Status(IStatus.ERROR, JSPFContentProperties.JSPCORE_ID, IStatus.ERROR, "Unable to set property", e)); //$NON-NLS-1$ - } - } - } - // Workbench preference may not be needed so leave out for now - // just set a preference in the instance scope - // if (!preferenceFound) { - // setWorkbenchPreference(key); - // } - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contentproperties/JSPFContentPropertiesManager.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contentproperties/JSPFContentPropertiesManager.java deleted file mode 100644 index 0b741c9f5d..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contentproperties/JSPFContentPropertiesManager.java +++ /dev/null @@ -1,255 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.web.core.internal.contentproperties; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResourceChangeEvent; -import org.eclipse.core.resources.IResourceChangeListener; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IResourceStatus; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.MultiStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.jsdt.web.core.internal.JSPCoreMessages; -import org.eclipse.wst.jsdt.web.core.internal.Logger; -import org.osgi.framework.Bundle; -import org.osgi.service.prefs.BackingStoreException; -import org.osgi.service.prefs.Preferences; - -public class JSPFContentPropertiesManager { - /** - * This job implementation is used to allow the resource change listener to - * schedule operations that need to modify the workspace. - */ - private class ContentPropertiesManagerJob extends Job { - private static final int PROPERTIES_UPDATE_DELAY = 500; - private List asyncChanges = new ArrayList(); - - public ContentPropertiesManagerJob() { - super(JSPCoreMessages.JSPFContentPropertiesManager_Updating); - setSystem(true); - setPriority(Job.INTERACTIVE); - } - - public void addChanges(Set newChanges) { - if (newChanges.isEmpty()) { - return; - } - synchronized (asyncChanges) { - asyncChanges.addAll(newChanges); - asyncChanges.notify(); - } - schedule(ContentPropertiesManagerJob.PROPERTIES_UPDATE_DELAY); - } - - public IProject getNextChange() { - synchronized (asyncChanges) { - return asyncChanges.isEmpty() ? null : (IProject) asyncChanges.remove(asyncChanges.size() - 1); - } - } - - @Override - protected IStatus run(IProgressMonitor monitor) { - MultiStatus result = new MultiStatus(JSPFContentProperties.JSPCORE_ID, IResourceStatus.FAILED_SETTING_CHARSET, JSPCoreMessages.JSPFContentPropertiesManager_Updating, null); - monitor = monitor == null ? new NullProgressMonitor() : monitor; - try { - monitor.beginTask(JSPCoreMessages.JSPFContentPropertiesManager_Updating, asyncChanges.size()); - try { - IProject next; - while ((next = getNextChange()) != null) { - // just exit if the system is shutting down or has - // been shut down - // it is too late to change the workspace at this - // point anyway - if (Platform.getBundle("org.eclipse.osgi").getState() != Bundle.ACTIVE) { - return Status.OK_STATUS; - } - try { - // save the preferences nodes - if (next.isAccessible()) { - // save content type preferences - Preferences projectPrefs = JSPFContentProperties.getPreferences(next, JSPFContentProperties.JSPCONTENTTYPE, false); - if (projectPrefs != null) { - projectPrefs.flush(); - } - // save language preferences - projectPrefs = JSPFContentProperties.getPreferences(next, JSPFContentProperties.JSPLANGUAGE, false); - if (projectPrefs != null) { - projectPrefs.flush(); - } - - } - } catch (BackingStoreException e) { - // we got an error saving - String detailMessage = NLS.bind(JSPCoreMessages.JSPFContentPropertiesManager_Problems_Updating, next.getFullPath()); - result.add(new Status(1 << (IResourceStatus.FAILED_SETTING_CHARSET % 100 / 33), ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_SETTING_CHARSET, detailMessage, e)); - } - } - monitor.worked(1); - } catch (OperationCanceledException e) { - throw e; - } - } finally { - monitor.done(); - } - return result; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.core.runtime.jobs.Job#shouldRun() - */ - @Override - public boolean shouldRun() { - synchronized (asyncChanges) { - return !asyncChanges.isEmpty(); - } - } - } - - class ResourceChangeListener implements IResourceChangeListener { - private void processEntryChanges(IResourceDelta projectDelta, Set projectsToSave) { - // check each resource with jsp fragment setting to see if it has - // been moved/deleted - boolean resourceChanges = false; - boolean resourceChanges2 = false; - - // project affected - IProject currentProject = (IProject) projectDelta.getResource(); - - resourceChanges = processPreferences(currentProject, JSPFContentProperties.JSPCONTENTTYPE, projectDelta, projectsToSave); - resourceChanges2 = processPreferences(currentProject, JSPFContentProperties.JSPLANGUAGE, projectDelta, projectsToSave); - - // if there was a preference key change, need to save preferences - if (resourceChanges || resourceChanges2) { - projectsToSave.add(currentProject); - } - } - - /** - * Goes through all the resource-dependent preferences associated with - * currentProject & key and updates the preference keys if needed based - * on projectDelta - * - * @param currentProject - * current project of the preferences to be looked at - * @param key - * current key/subcategory of the preferences to be looked at - * @param projectDelta - * the changes to process the preference keys against - * @param projectsToSave - * the projects that need to be updated/saved - * @return true if currentProject's preferences were modified - */ - private boolean processPreferences(IProject currentProject, String key, IResourceDelta projectDelta, Set projectsToSave) { - boolean resourceChanges = false; - - // get the project-key preference node - Preferences projectPrefs = JSPFContentProperties.getPreferences(currentProject, key, false); - if (projectPrefs == null) { - // no preferences for this project-key, just bail - return false; - } - String[] affectedResources; - try { - affectedResources = projectPrefs.keys(); - } catch (BackingStoreException e) { - // problems with the project scope... we gonna miss the - // changes (but will log) - Logger.log(Logger.WARNING_DEBUG, "Problem retreiving JSP Fragment preferences", e); //$NON-NLS-1$ - return false; - } - - // go through each preference key (which is really a file name) - for (int i = 0; i < affectedResources.length; i++) { - // see if preference key/file name was file that was changed - IResourceDelta memberDelta = projectDelta.findMember(new Path(affectedResources[i])); - // no changes for the given resource - if (memberDelta == null) { - continue; - } - if (memberDelta.getKind() == IResourceDelta.REMOVED) { - resourceChanges = true; - // remove the setting for the original location - String currentValue = projectPrefs.get(affectedResources[i], null); - projectPrefs.remove(affectedResources[i]); - if ((memberDelta.getFlags() & IResourceDelta.MOVED_TO) != 0) { - // if moving, copy the setting for the new location - IProject targetProject = ResourcesPlugin.getWorkspace().getRoot().getProject(memberDelta.getMovedToPath().segment(0)); - Preferences targetPrefs = JSPFContentProperties.getPreferences(targetProject, key, true); - targetPrefs.put(JSPFContentProperties.getKeyFor(memberDelta.getMovedToPath()), currentValue); - if (targetProject != currentProject) { - projectsToSave.add(targetProject); - } - } - } - } - return resourceChanges; - } - - /** - * For any change to the encoding file or any resource with encoding - * set, just discard the cache for the corresponding project. - */ - public void resourceChanged(IResourceChangeEvent event) { - IResourceDelta delta = event.getDelta(); - if (delta == null) { - return; - } - IResourceDelta[] projectDeltas = delta.getAffectedChildren(); - // process each project in the delta - Set projectsToSave = new HashSet(); - for (int i = 0; i < projectDeltas.length; i++) { - // nothing to do if a project has been added/removed/moved - if (projectDeltas[i].getKind() == IResourceDelta.CHANGED && (projectDeltas[i].getFlags() & IResourceDelta.OPEN) == 0) { - processEntryChanges(projectDeltas[i], projectsToSave); - } - } - fJob.addChanges(projectsToSave); - } - } - - private static JSPFContentPropertiesManager _instance = null; - - public synchronized static void shutdown() { - ResourcesPlugin.getWorkspace().removeResourceChangeListener(JSPFContentPropertiesManager._instance.fResourceChangeListener); - JSPFContentPropertiesManager._instance = null; - } - - public synchronized static void startup() { - JSPFContentPropertiesManager._instance = new JSPFContentPropertiesManager(); - ResourcesPlugin.getWorkspace().addResourceChangeListener(JSPFContentPropertiesManager._instance.fResourceChangeListener, IResourceChangeEvent.POST_CHANGE); - } - - ContentPropertiesManagerJob fJob; - - private IResourceChangeListener fResourceChangeListener; - - public JSPFContentPropertiesManager() { - super(); - fResourceChangeListener = new ResourceChangeListener(); - fJob = new ContentPropertiesManagerJob(); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/ByteReader.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/ByteReader.java deleted file mode 100644 index b7871cc322..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/ByteReader.java +++ /dev/null @@ -1,116 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.jsdt.web.core.internal.contenttype; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; - -import org.eclipse.wst.sse.core.internal.encoding.CodedIO; - -/** - * This is an "adapter" class, simply to get in input stream to act like a - * reader. We could not use InputStreamReader directly because its internal - * buffers are not controllable, and it sometimes pulls too much out of input - * stream (even when it wasn't needed for our purposes). - * - * The use of this class is highly specialized and by not means meant to be - * general purpose. Its use is restricted to those cases where the input stream - * can be regarded as ascii just long enough to determine what the real encoding - * should be. - */ - -public class ByteReader extends Reader { - - public static final int DEFAULT_BUFFER_SIZE = CodedIO.MAX_BUF_SIZE; - - protected byte[] fBuffer; - - protected InputStream fInputStream; - - protected ByteReader() { - super(); - } - - public ByteReader(InputStream inputStream) { - this(inputStream, ByteReader.DEFAULT_BUFFER_SIZE); - if (!inputStream.markSupported()) { - throw new IllegalArgumentException("ByteReader is required to have a resettable stream"); //$NON-NLS-1$ - } - } - - public ByteReader(InputStream inputStream, int size) { - this.fInputStream = inputStream; - if (!inputStream.markSupported()) { - throw new IllegalArgumentException("ByteReader is required to have a resettable stream"); //$NON-NLS-1$ - } - this.fBuffer = new byte[size]; - - } - - @Override - public void close() throws IOException { - this.fInputStream.close(); - } - - @Override - public void mark(int readAheadLimit) { - this.fInputStream.mark(readAheadLimit); - } - - @Override - public boolean markSupported() { - return true; - } - - @Override - public int read() throws IOException { - int b0 = this.fInputStream.read(); - return (b0 & 0x00FF); - } - - @Override - public int read(char ch[], int offset, int length) throws IOException { - if (length > this.fBuffer.length) { - length = this.fBuffer.length; - } - - int count = this.fInputStream.read(this.fBuffer, 0, length); - - for (int i = 0; i < count; i++) { - int b0 = this.fBuffer[i]; - // the 0x00FF is to "lose" the negative bits filled in the byte to - // int conversion - // (and which would be there if cast directly from byte to char). - char c0 = (char) (b0 & 0x00FF); - ch[offset + i] = c0; - } - return count; - } - - @Override - public boolean ready() throws IOException { - return this.fInputStream.available() > 0; - } - - @Override - public void reset() throws IOException { - this.fInputStream.reset(); - } - - @Override - public long skip(long n) throws IOException { - return this.fInputStream.skip(n); - } - -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/ContentDescriberForJSP.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/ContentDescriberForJSP.java deleted file mode 100644 index 52f1a0da84..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/ContentDescriberForJSP.java +++ /dev/null @@ -1,212 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004-2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.web.core.internal.contenttype; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; - -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.content.IContentDescriber; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.ITextContentDescriber; -import org.eclipse.wst.html.core.internal.contenttype.HTMLResourceEncodingDetector; -import org.eclipse.wst.sse.core.internal.encoding.EncodingMemento; -import org.eclipse.wst.sse.core.internal.encoding.IContentDescriptionExtended; -import org.eclipse.wst.sse.core.internal.encoding.IResourceCharsetDetector; - -public final class ContentDescriberForJSP implements ITextContentDescriber { - - final private static QualifiedName[] SUPPORTED_OPTIONS = { IContentDescription.CHARSET, IContentDescription.BYTE_ORDER_MARK, IContentDescriptionExtended.DETECTED_CHARSET, IContentDescriptionExtended.UNSUPPORTED_CHARSET, IContentDescriptionExtended.APPROPRIATE_DEFAULT }; - - private void calculateSupportedOptions(InputStream contents, IContentDescription description) throws IOException { - if (isRelevent(description)) { - IResourceCharsetDetector detector = getDetector(); - detector.set(contents); - handleCalculations(description, detector); - } - } - - /** - * @param contents - * @param description - * @throws IOException - */ - private void calculateSupportedOptions(Reader contents, IContentDescription description) throws IOException { - if (isRelevent(description)) { - IResourceCharsetDetector detector = getDetector(); - detector.set(contents); - handleCalculations(description, detector); - } - } - - private int computeValidity(InputStream inputStream) { - // currently no contents specific check for valid HTML contents - // (this may change once we add XHTML content type) - return IContentDescriber.INDETERMINATE; - } - - private int computeValidity(Reader reader) { - // currently no contents specific check for valid HTML contents - // (this may change once we add XHTML content type) - return IContentDescriber.INDETERMINATE; - } - - public int describe(InputStream contents, IContentDescription description) throws IOException { - int result = IContentDescriber.INDETERMINATE; - - if (description == null) { - result = computeValidity(contents); - } else { - calculateSupportedOptions(contents, description); - // assummming we should return same 'validity' value we did - // when called before. (technically, could be a performance issue - // in future, so might want to check if any 'ol value would - // be ok here. - result = computeValidity(contents); - } - - return result; - } - - public int describe(Reader contents, IContentDescription description) throws IOException { - int result = IContentDescriber.INDETERMINATE; - - if (description == null) { - result = computeValidity(contents); - } else { - calculateSupportedOptions(contents, description); - // assummming we should return same 'validity' value we did - // when called before. (technically, could be a performance issue - // in future, so might want to check if hard coded 'valid' would - // be ok here. - result = computeValidity(contents); - } - - return result; - } - - private IResourceCharsetDetector getDetector() { - - return new HTMLResourceEncodingDetector(); - - } - - public QualifiedName[] getSupportedOptions() { - - return ContentDescriberForJSP.SUPPORTED_OPTIONS; - } - - /** - * @param description - * @param detector - * @throws IOException - */ - private void handleCalculations(IContentDescription description, IResourceCharsetDetector detector) throws IOException { - - EncodingMemento encodingMemento = ((HTMLResourceEncodingDetector) detector).getEncodingMemento(); - // TODO: I need to verify to see if this BOM work is always done - // by text type. - Object detectedByteOrderMark = encodingMemento.getUnicodeBOM(); - if (detectedByteOrderMark != null) { - Object existingByteOrderMark = description.getProperty(IContentDescription.BYTE_ORDER_MARK); - // not sure why would ever be different, so if is different, may - // need to "push" up into base. - if (!detectedByteOrderMark.equals(existingByteOrderMark)) { - description.setProperty(IContentDescription.BYTE_ORDER_MARK, detectedByteOrderMark); - } - } - - if (!encodingMemento.isValid()) { - /* - * note: after setting here, its the mere presence of - * IContentDescriptionExtended.UNSUPPORTED_CHARSET in the resource's - * description that can be used to determine if invalid in those - * cases, the "detected" property contains an "appropriate default" - * to use. - */ - description.setProperty(IContentDescriptionExtended.UNSUPPORTED_CHARSET, encodingMemento.getInvalidEncoding()); - description.setProperty(IContentDescriptionExtended.APPROPRIATE_DEFAULT, encodingMemento.getAppropriateDefault()); - } - - Object detectedCharset = encodingMemento.getDetectedCharsetName(); - Object javaCharset = encodingMemento.getJavaCharsetName(); - - // we always include detected, if its different than java - handleDetectedSpecialCase(description, detectedCharset, javaCharset); - - if (javaCharset != null) { - Object existingCharset = description.getProperty(IContentDescription.CHARSET); - if (javaCharset.equals(existingCharset)) { - handleDetectedSpecialCase(description, detectedCharset, javaCharset); - } else { - // we may need to add what we found, but only need to add - // if different from default.the - Object defaultCharset = detector.getSpecDefaultEncoding(); - if (defaultCharset != null) { - if (!defaultCharset.equals(javaCharset)) { - description.setProperty(IContentDescription.CHARSET, javaCharset); - } - } else { - // assuming if there is no spec default, we always need to - // add, I'm assuming - description.setProperty(IContentDescription.CHARSET, javaCharset); - } - } - } - - } - - private void handleDetectedSpecialCase(IContentDescription description, Object detectedCharset, Object javaCharset) { - // since equal, we don't need to add, but if our detected version is - // different than - // javaCharset, then we should add it. This will happen, for example, - // if there's - // differences in case, or differences due to override properties - if (detectedCharset != null) { - // if (!detectedCharset.equals(javaCharset)) { - // description.setProperty(IContentDescriptionExtended.DETECTED_CHARSET, - // detectedCharset); - // } - - // Once we detected a charset, we should set the property even - // though it's the same as javaCharset - // because there are clients that rely on this property to - // determine if the charset is actually detected in file or not. - description.setProperty(IContentDescriptionExtended.DETECTED_CHARSET, detectedCharset); - } - } - - /** - * @param description - * @return - */ - private boolean isRelevent(IContentDescription description) { - boolean result = false; - if (description == null) { - result = false; - } else if (description.isRequested(IContentDescription.BYTE_ORDER_MARK)) { - result = true; - } else if (description.isRequested(IContentDescription.CHARSET)) { - result = true; - } else if (description.isRequested(IContentDescriptionExtended.APPROPRIATE_DEFAULT)) { - result = true; - } else if (description.isRequested(IContentDescriptionExtended.DETECTED_CHARSET)) { - result = true; - } else if (description.isRequested(IContentDescriptionExtended.UNSUPPORTED_CHARSET)) { - result = true; - } - // else if - // (description.isRequested(IContentDescriptionExtended.ENCODING_MEMENTO)) - // result = true; - return result; - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/HeadParserToken.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/HeadParserToken.java deleted file mode 100644 index e0bea58e82..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/HeadParserToken.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.jsdt.web.core.internal.contenttype; - -public class HeadParserToken { - private int fStart; - - private String fText; - private String fType; - - protected HeadParserToken() { - super(); - } - - public HeadParserToken(String type, int start, String text) { - this(); - fType = type; - fStart = start; - fText = text; - - } - - public String getText() { - return fText; - } - - public String getType() { - return fType; - } - - @Override - public String toString() { - return ("text: " + fText + " offset: " + fStart + " type: " + fType); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/IntStack.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/IntStack.java deleted file mode 100644 index 1ee2e4f44b..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/IntStack.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2001, 2004 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Jens Lukowski/Innoopract - initial renaming/restructuring - * - *******************************************************************************/ -package org.eclipse.wst.jsdt.web.core.internal.contenttype; - -/* - * - * A non-resizable class implementing the behavior of java.util.Stack, but - * directly for the <code> integer </code> primitive. - */ -import java.util.EmptyStackException; - -public class IntStack { - private int[] list = null; - - private int size = 0; - - public IntStack() { - this(100); - } - - public IntStack(int maxdepth) { - super(); - list = new int[maxdepth]; - initialize(); - } - - public void clear() { - initialize(); - } - - public boolean empty() { - return size == 0; - } - - public int get(int slot) { - return list[slot]; - } - - private void initialize() { - for (int i = 0; i < list.length; i++) { - list[i] = -1; - } - } - - /** - * Returns the int at the top of the stack without removing it - * - * @return int at the top of this stack. - * @exception EmptyStackException - * when empty. - */ - public int peek() { - if (size == 0) { - throw new EmptyStackException(); - } - return list[size - 1]; - } - - /** - * Removes and returns the int at the top of the stack - * - * @return int at the top of this stack. - * @exception EmptyStackException - * when empty. - */ - public int pop() { - int value = peek(); - list[size - 1] = -1; - size--; - return value; - } - - /** - * Pushes an item onto the top of this stack. - * - * @param newValue - - * the int to be pushed onto this stack. - * @return the <code>newValue</code> argument. - */ - public int push(int newValue) { - if (size == list.length) { - throw new StackOverflowError(); - } - list[size++] = newValue; - return newValue; - } - - public int size() { - return list.length; - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/JSPHeadTokenizer.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/JSPHeadTokenizer.java deleted file mode 100644 index 201b42dde5..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/JSPHeadTokenizer.java +++ /dev/null @@ -1,3023 +0,0 @@ -/* The following code was generated by JFlex 1.4 on 9/18/06 2:12 PM */ - -/******************************************************************************* - * Copyright (c) 2005 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 - *******************************************************************************/ -/*nlsXXX*/ -package org.eclipse.wst.jsdt.web.core.internal.contenttype; - -import java.io.IOException; -import java.io.Reader; - -import org.eclipse.wst.xml.core.internal.contenttype.EncodingParserConstants; -import org.eclipse.wst.xml.core.internal.contenttype.XMLHeadTokenizerConstants; - -/** - * This class is a scanner generated by <a href="http://www.jflex.de/">JFlex</a> - * 1.4 on 9/18/06 2:12 PM from the specification file - * <tt>D:/builds/Workspaces/WTP15maintenance/org.eclipse.wst.jsdt.web.core/DevTimeSupport/HeadParsers/JSPHeadTokenizer.jFlex</tt> - */ -public class JSPHeadTokenizer { - - public static final int DQ_STRING = 8; - - private final static int MAX_TO_SCAN = 8000; - - public static final int QuotedAttributeValue = 6; - public static final int SQ_STRING = 10; - public static final int ST_PAGE_DIRECTIVE = 4; - public static final int ST_XMLDecl = 2; - public static final int UnDelimitedString = 12; - /** This character denotes the end of file */ - public static final int YYEOF = -1; - /** lexical states */ - public static final int YYINITIAL = 0; - - /** - * Translates DFA states to action switch labels. - */ - private static final int[] ZZ_ACTION = JSPHeadTokenizer.zzUnpackAction(); - - private static final String ZZ_ACTION_PACKED_0 = "\10\0\20\1\2\2\1\1\1\3\1\4\1\5\1\6" + "\1\5\1\7\2\5\1\7\1\10\2\11\4\0\1\12" + "\1\13\6\0\1\14\5\0\1\15\1\16\1\0\1\17" + "\1\0\1\20\4\0\1\21\36\0\1\22\20\0\1\23" + "\2\0\1\24\6\0\1\25\1\26\22\0\1\27\5\0" + "\1\30\52\0\1\31\5\0\1\32\12\0\1\32"; - - /** initial size of the lookahead buffer */ - private static final int ZZ_BUFFERSIZE = 8192; - - /** - * Translates characters to character classes - */ - private static final char[] ZZ_CMAP = JSPHeadTokenizer.zzUnpackCMap(JSPHeadTokenizer.ZZ_CMAP_PACKED); - - /** - * Translates characters to character classes - */ - private static final String ZZ_CMAP_PACKED = "\11\0\1\6\1\11\2\0\1\10\22\0\1\34\1\17\1\37\2\0" + "\1\51\1\0\1\40\6\0\1\43\1\33\1\0\1\47\1\0\1\44" + "\5\0\1\50\1\41\1\0\1\12\1\7\1\56\1\13\1\52\1\53" + "\1\31\1\22\1\20\1\26\1\0\1\46\1\27\1\32\1\54\1\0" + "\1\16\1\15\1\35\1\21\1\25\1\0\1\45\1\36\1\23\1\30" + "\1\55\1\42\1\14\1\24\7\0\1\53\1\31\1\22\1\20\1\26" + "\1\0\1\46\1\27\1\32\1\54\1\0\1\16\1\15\1\35\1\21" + "\1\25\1\0\1\45\1\36\1\23\1\30\1\55\1\42\1\14\1\24" + "\101\0\1\4\3\0\1\5\17\0\1\3\16\0\1\1\20\0\1\3" + "\16\0\1\1\1\2\170\0\1\2\ufe87\0"; - - /* error messages for the codes above */ - private static final String ZZ_ERROR_MSG[] = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; - - /** - * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l - * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l at the - * beginning of a line l is of the form l = 2*k, k a non negative integer - */ - private static final int ZZ_LEXSTATE[] = { 0, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7 }; - - private static final int ZZ_NO_MATCH = 1; - private static final int ZZ_PUSHBACK_2BIG = 2; - /* error codes */ - private static final int ZZ_UNKNOWN_ERROR = 0; - - private static int[] zzUnpackAction() { - int[] result = new int[212]; - int offset = 0; - offset = JSPHeadTokenizer.zzUnpackAction(JSPHeadTokenizer.ZZ_ACTION_PACKED_0, offset, result); - return result; - } - - private static int zzUnpackAction(String packed, int offset, int[] result) { - int i = 0; /* index in packed string */ - int j = offset; /* index in unpacked array */ - int l = packed.length(); - while (i < l) { - int count = packed.charAt(i++); - int value = packed.charAt(i++); - do { - result[j++] = value; - } while (--count > 0); - } - return j; - } - - /** - * Unpacks the compressed character translation table. - * - * @param packed - * the packed character translation table - * @return the unpacked character translation table - */ - private static char[] zzUnpackCMap(String packed) { - char[] map = new char[0x10000]; - int i = 0; /* index in packed string */ - int j = 0; /* index in unpacked array */ - while (i < 192) { - int count = packed.charAt(i++); - char value = packed.charAt(i++); - do { - map[j++] = value; - } while (--count > 0); - } - return map; - } - - // state stack for easier state handling - private IntStack fStateStack = new IntStack(); - - private boolean hasMore = true; - - private boolean isWML; - - private boolean isXHTML; - - StringBuffer string = new StringBuffer(); - - private String valueText = null; - - /** number of newlines encountered up to the start of the matched text */ - // private int yyline; - /** the number of characters up to the start of the matched text */ - private int yychar; - - /** - * the number of characters from the last newline up to the start of the - * matched text - */ - // private int yycolumn; - /** - * zzAtBOL == true <=> the scanner is currently at the beginning of a line - */ - private boolean zzAtBOL = true; - - /** zzAtEOF == true <=> the scanner is at the EOF */ - private boolean zzAtEOF; - - /** - * this buffer contains the current text to be matched and is the source of - * the yytext() string - */ - private char zzBuffer[] = new char[JSPHeadTokenizer.ZZ_BUFFERSIZE]; - - /** the current text position in the buffer */ - private int zzCurrentPos; - - /* user code: */ - - /** - * endRead marks the last character in the buffer, that has been read from - * input - */ - private int zzEndRead; - /** denotes if the user-EOF-code has already been executed */ - private boolean zzEOFDone; - /** the current lexical state */ - private int zzLexicalState = JSPHeadTokenizer.YYINITIAL; - /** the textposition at the last accepting state */ - private int zzMarkedPos; - /** the textposition at the last state to be included in yytext */ - private int zzPushbackPos; - /** the input device */ - private java.io.Reader zzReader; - /** startRead marks the beginning of the yytext() string in the buffer */ - private int zzStartRead; - - /** the current state of the DFA */ - private int zzState; - - public JSPHeadTokenizer() { - super(); - } - - /** - * Creates a new scanner. There is also java.io.Reader version of this - * constructor. - * - * @param in - * the java.io.Inputstream to read input from. - */ - public JSPHeadTokenizer(java.io.InputStream in) { - this(new java.io.InputStreamReader(in)); - } - - /** - * Creates a new scanner There is also a java.io.InputStream version of this - * constructor. - * - * @param in - * the java.io.Reader to read input from. - */ - public JSPHeadTokenizer(java.io.Reader in) { - this.zzReader = in; - } - - private HeadParserToken createToken(String context, int start, String text) { - return new HeadParserToken(context, start, text); - } - - public final HeadParserToken getNextToken() throws IOException { - String context = null; - context = primGetNextToken(); - HeadParserToken result = null; - if (valueText != null) { - result = createToken(context, yychar, valueText); - valueText = null; - } else { - result = createToken(context, yychar, yytext()); - } - return result; - } - - public final boolean hasMoreTokens() { - return hasMore && yychar < JSPHeadTokenizer.MAX_TO_SCAN; - } - - public boolean isWML() { - return isWML; - } - - public boolean isXHTML() { - return isXHTML; - } - - private void popState() { - yybegin(fStateStack.pop()); - } - - /** - * Resumes scanning until the next regular expression is matched, the end of - * input is encountered or an I/O-Error occurs. - * - * @return the next token - * @exception java.io.IOException - * if any I/O-Error occurs - */ - public String primGetNextToken() throws java.io.IOException { - int zzInput; - int zzAction; - - // cached fields: - int zzCurrentPosL; - int zzMarkedPosL; - int zzEndReadL = zzEndRead; - char[] zzBufferL = zzBuffer; - char[] zzCMapL = JSPHeadTokenizer.ZZ_CMAP; - - while (true) { - zzMarkedPosL = zzMarkedPos; - - yychar += zzMarkedPosL - zzStartRead; - - if (zzMarkedPosL > zzStartRead) { - switch (zzBufferL[zzMarkedPosL - 1]) { - case '\n': - case '\u000B': - case '\u000C': - case '\u0085': - case '\u2028': - case '\u2029': - zzAtBOL = true; - break; - case '\r': - if (zzMarkedPosL < zzEndReadL) { - zzAtBOL = zzBufferL[zzMarkedPosL] != '\n'; - } else if (zzAtEOF) { - zzAtBOL = false; - } else { - boolean eof = zzRefill(); - zzMarkedPosL = zzMarkedPos; - zzBufferL = zzBuffer; - if (eof) { - zzAtBOL = false; - } else { - zzAtBOL = zzBufferL[zzMarkedPosL] != '\n'; - } - } - break; - default: - zzAtBOL = false; - } - } - zzAction = -1; - - zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; - - if (zzAtBOL) { - zzState = JSPHeadTokenizer.ZZ_LEXSTATE[zzLexicalState + 1]; - } else { - zzState = JSPHeadTokenizer.ZZ_LEXSTATE[zzLexicalState]; - } - - zzForAction: { - while (true) { - - if (zzCurrentPosL < zzEndReadL) { - zzInput = zzBufferL[zzCurrentPosL++]; - } else if (zzAtEOF) { - zzInput = JSPHeadTokenizer.YYEOF; - break zzForAction; - } else { - // store back cached positions - zzCurrentPos = zzCurrentPosL; - zzMarkedPos = zzMarkedPosL; - boolean eof = zzRefill(); - // get translated positions and possibly new buffer - zzCurrentPosL = zzCurrentPos; - zzMarkedPosL = zzMarkedPos; - zzBufferL = zzBuffer; - zzEndReadL = zzEndRead; - if (eof) { - zzInput = JSPHeadTokenizer.YYEOF; - break zzForAction; - } else { - zzInput = zzBufferL[zzCurrentPosL++]; - } - } - zzInput = zzCMapL[zzInput]; - - boolean zzIsFinal = false; - boolean zzNoLookAhead = false; - - zzForNext: { - switch (zzState) { - case 0: - switch (zzInput) { - case 10: - zzIsFinal = true; - zzState = 9; - break zzForNext; - default: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 8; - break zzForNext; - } - - case 1: - switch (zzInput) { - case 1: - zzIsFinal = true; - zzState = 10; - break zzForNext; - case 2: - zzIsFinal = true; - zzState = 11; - break zzForNext; - case 3: - zzIsFinal = true; - zzState = 12; - break zzForNext; - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzState = 13; - break zzForNext; - case 10: - zzIsFinal = true; - zzState = 14; - break zzForNext; - default: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 8; - break zzForNext; - } - - case 2: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzState = 15; - break zzForNext; - case 11: - zzIsFinal = true; - zzState = 16; - break zzForNext; - case 22: - zzIsFinal = true; - zzState = 17; - break zzForNext; - case 45: - zzIsFinal = true; - zzState = 18; - break zzForNext; - default: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 8; - break zzForNext; - } - - case 3: - switch (zzInput) { - case 14: - zzIsFinal = true; - zzState = 19; - break zzForNext; - case 18: - zzIsFinal = true; - zzState = 20; - break zzForNext; - case 21: - zzIsFinal = true; - zzState = 21; - break zzForNext; - case 27: - zzIsFinal = true; - zzState = 22; - break zzForNext; - case 41: - zzIsFinal = true; - zzState = 23; - break zzForNext; - default: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 8; - break zzForNext; - } - - case 4: - switch (zzInput) { - case 6: - case 8: - case 28: - zzIsFinal = true; - zzState = 25; - break zzForNext; - case 9: - zzIsFinal = true; - zzState = 26; - break zzForNext; - case 31: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 27; - break zzForNext; - case 32: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 28; - break zzForNext; - default: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 24; - break zzForNext; - } - - case 5: - switch (zzInput) { - case 8: - case 9: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 30; - break zzForNext; - case 11: - zzIsFinal = true; - zzState = 31; - break zzForNext; - case 31: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 32; - break zzForNext; - case 32: - zzIsFinal = true; - zzState = 33; - break zzForNext; - case 41: - zzIsFinal = true; - zzState = 34; - break zzForNext; - default: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 29; - break zzForNext; - } - - case 6: - switch (zzInput) { - case 8: - case 9: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 30; - break zzForNext; - case 41: - zzIsFinal = true; - zzState = 34; - break zzForNext; - case 32: - zzIsFinal = true; - zzState = 35; - break zzForNext; - default: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 29; - break zzForNext; - } - - case 7: - switch (zzInput) { - case 11: - case 41: - zzIsFinal = true; - zzState = 34; - break zzForNext; - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 36; - break zzForNext; - case 31: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 37; - break zzForNext; - case 32: - zzIsFinal = true; - zzState = 38; - break zzForNext; - default: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 29; - break zzForNext; - } - - case 9: - switch (zzInput) { - case 15: - zzState = 39; - break zzForNext; - case 23: - zzState = 40; - break zzForNext; - case 41: - zzState = 41; - break zzForNext; - case 44: - zzState = 42; - break zzForNext; - default: - break zzForAction; - } - - case 10: - switch (zzInput) { - case 2: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 43; - break zzForNext; - default: - break zzForAction; - } - - case 11: - switch (zzInput) { - case 1: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 44; - break zzForNext; - default: - break zzForAction; - } - - case 12: - switch (zzInput) { - case 4: - zzState = 45; - break zzForNext; - default: - break zzForAction; - } - - case 13: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 46; - break zzForNext; - case 10: - zzState = 47; - break zzForNext; - default: - break zzForAction; - } - - case 14: - switch (zzInput) { - case 15: - zzState = 39; - break zzForNext; - case 23: - zzState = 40; - break zzForNext; - case 41: - zzState = 41; - break zzForNext; - case 44: - zzState = 42; - break zzForNext; - case 11: - zzState = 48; - break zzForNext; - default: - break zzForAction; - } - - case 15: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 49; - break zzForNext; - case 11: - zzState = 50; - break zzForNext; - default: - break zzForAction; - } - - case 16: - switch (zzInput) { - case 46: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 51; - break zzForNext; - default: - break zzForAction; - } - - case 17: - switch (zzInput) { - case 29: - zzState = 52; - break zzForNext; - default: - break zzForAction; - } - - case 18: - switch (zzInput) { - case 22: - zzState = 53; - break zzForNext; - default: - break zzForAction; - } - - case 19: - switch (zzInput) { - case 43: - zzState = 54; - break zzForNext; - default: - break zzForAction; - } - - case 20: - switch (zzInput) { - case 17: - zzState = 55; - break zzForNext; - default: - break zzForAction; - } - - case 21: - switch (zzInput) { - case 43: - zzState = 56; - break zzForNext; - default: - break zzForAction; - } - - case 22: - switch (zzInput) { - case 46: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 57; - break zzForNext; - default: - break zzForAction; - } - - case 23: - switch (zzInput) { - case 46: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 58; - break zzForNext; - default: - break zzForAction; - } - - case 25: - switch (zzInput) { - case 6: - case 8: - case 28: - zzIsFinal = true; - zzState = 25; - break zzForNext; - case 9: - zzState = 59; - break zzForNext; - default: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 24; - break zzForNext; - } - - case 26: - switch (zzInput) { - case 6: - case 8: - case 28: - zzIsFinal = true; - zzState = 25; - break zzForNext; - case 9: - zzState = 59; - break zzForNext; - default: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 24; - break zzForNext; - } - - case 31: - switch (zzInput) { - case 46: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 60; - break zzForNext; - default: - break zzForAction; - } - - case 33: - switch (zzInput) { - case 10: - zzState = 61; - break zzForNext; - default: - break zzForAction; - } - - case 34: - switch (zzInput) { - case 46: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 62; - break zzForNext; - default: - break zzForAction; - } - - case 35: - switch (zzInput) { - case 10: - zzState = 61; - break zzForNext; - default: - break zzForAction; - } - - case 38: - switch (zzInput) { - case 10: - zzState = 61; - break zzForNext; - default: - break zzForAction; - } - - case 39: - switch (zzInput) { - case 16: - zzState = 63; - break zzForNext; - default: - break zzForAction; - } - - case 40: - switch (zzInput) { - case 19: - zzState = 64; - break zzForNext; - default: - break zzForAction; - } - - case 41: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 41; - break zzForNext; - case 42: - zzState = 65; - break zzForNext; - default: - break zzForAction; - } - - case 42: - switch (zzInput) { - case 30: - zzState = 66; - break zzForNext; - default: - break zzForAction; - } - - case 45: - switch (zzInput) { - case 5: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 67; - break zzForNext; - default: - break zzForAction; - } - - case 46: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 46; - break zzForNext; - case 10: - zzState = 47; - break zzForNext; - default: - break zzForAction; - } - - case 47: - switch (zzInput) { - case 11: - zzState = 48; - break zzForNext; - default: - break zzForAction; - } - - case 48: - switch (zzInput) { - case 12: - zzState = 68; - break zzForNext; - default: - break zzForAction; - } - - case 49: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 49; - break zzForNext; - case 11: - zzState = 50; - break zzForNext; - default: - break zzForAction; - } - - case 50: - switch (zzInput) { - case 46: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 51; - break zzForNext; - default: - break zzForAction; - } - - case 52: - switch (zzInput) { - case 18: - zzState = 69; - break zzForNext; - default: - break zzForAction; - } - - case 53: - switch (zzInput) { - case 37: - zzState = 70; - break zzForNext; - default: - break zzForAction; - } - - case 54: - switch (zzInput) { - case 29: - zzState = 71; - break zzForNext; - default: - break zzForAction; - } - - case 55: - switch (zzInput) { - case 29: - zzState = 72; - break zzForNext; - default: - break zzForAction; - } - - case 56: - switch (zzInput) { - case 38: - zzState = 73; - break zzForNext; - default: - break zzForAction; - } - - case 59: - switch (zzInput) { - case 6: - case 8: - case 28: - zzIsFinal = true; - zzState = 25; - break zzForNext; - case 9: - zzState = 59; - break zzForNext; - default: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 24; - break zzForNext; - } - - case 61: - switch (zzInput) { - case 32: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 30; - break zzForNext; - default: - break zzForAction; - } - - case 63: - switch (zzInput) { - case 17: - zzState = 74; - break zzForNext; - default: - break zzForAction; - } - - case 64: - switch (zzInput) { - case 13: - zzState = 75; - break zzForNext; - default: - break zzForAction; - } - - case 65: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 65; - break zzForNext; - case 21: - zzState = 76; - break zzForNext; - default: - break zzForAction; - } - - case 66: - switch (zzInput) { - case 21: - zzState = 77; - break zzForNext; - default: - break zzForAction; - } - - case 68: - switch (zzInput) { - case 13: - zzState = 78; - break zzForNext; - default: - break zzForAction; - } - - case 69: - switch (zzInput) { - case 17: - zzState = 79; - break zzForNext; - default: - break zzForAction; - } - - case 70: - switch (zzInput) { - case 30: - zzState = 80; - break zzForNext; - default: - break zzForAction; - } - - case 71: - switch (zzInput) { - case 38: - zzState = 81; - break zzForNext; - default: - break zzForAction; - } - - case 72: - switch (zzInput) { - case 19: - zzState = 82; - break zzForNext; - default: - break zzForAction; - } - - case 73: - switch (zzInput) { - case 22: - zzState = 83; - break zzForNext; - default: - break zzForAction; - } - - case 74: - switch (zzInput) { - case 18: - zzState = 84; - break zzForNext; - default: - break zzForAction; - } - - case 75: - switch (zzInput) { - case 14: - zzState = 85; - break zzForNext; - default: - break zzForAction; - } - - case 76: - switch (zzInput) { - case 43: - zzState = 86; - break zzForNext; - default: - break zzForAction; - } - - case 77: - switch (zzInput) { - case 33: - zzState = 87; - break zzForNext; - default: - break zzForAction; - } - - case 78: - switch (zzInput) { - case 14: - zzState = 88; - break zzForNext; - default: - break zzForAction; - } - - case 79: - switch (zzInput) { - case 16: - zzState = 89; - break zzForNext; - default: - break zzForAction; - } - - case 80: - switch (zzInput) { - case 26: - zzState = 90; - break zzForNext; - default: - break zzForAction; - } - - case 81: - switch (zzInput) { - case 24: - zzState = 91; - break zzForNext; - default: - break zzForAction; - } - - case 82: - switch (zzInput) { - case 22: - zzState = 92; - break zzForNext; - default: - break zzForAction; - } - - case 83: - switch (zzInput) { - case 22: - zzState = 93; - break zzForNext; - default: - break zzForAction; - } - - case 84: - switch (zzInput) { - case 19: - zzState = 94; - break zzForNext; - default: - break zzForAction; - } - - case 85: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 85; - break zzForNext; - case 12: - zzState = 95; - break zzForNext; - default: - break zzForAction; - } - - case 86: - switch (zzInput) { - case 38: - zzState = 96; - break zzForNext; - default: - break zzForAction; - } - - case 87: - switch (zzInput) { - case 16: - zzState = 97; - break zzForNext; - default: - break zzForAction; - } - - case 88: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzState = 98; - break zzForNext; - default: - break zzForAction; - } - - case 89: - switch (zzInput) { - case 26: - zzState = 99; - break zzForNext; - default: - break zzForAction; - } - - case 90: - switch (zzInput) { - case 17: - zzState = 100; - break zzForNext; - default: - break zzForAction; - } - - case 91: - switch (zzInput) { - case 43: - zzState = 101; - break zzForNext; - default: - break zzForAction; - } - - case 92: - switch (zzInput) { - case 29: - zzState = 102; - break zzForNext; - default: - break zzForAction; - } - - case 93: - switch (zzInput) { - case 29: - zzState = 103; - break zzForNext; - default: - break zzForAction; - } - - case 94: - switch (zzInput) { - case 20: - zzState = 104; - break zzForNext; - default: - break zzForAction; - } - - case 95: - switch (zzInput) { - case 13: - zzState = 105; - break zzForNext; - default: - break zzForAction; - } - - case 96: - switch (zzInput) { - case 22: - zzState = 106; - break zzForNext; - default: - break zzForAction; - } - - case 97: - switch (zzInput) { - case 26: - zzState = 107; - break zzForNext; - default: - break zzForAction; - } - - case 98: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzState = 98; - break zzForNext; - default: - break zzForAction; - } - - case 99: - switch (zzInput) { - case 29: - zzState = 108; - break zzForNext; - default: - break zzForAction; - } - - case 100: - switch (zzInput) { - case 29: - zzState = 109; - break zzForNext; - default: - break zzForAction; - } - - case 101: - switch (zzInput) { - case 38: - zzState = 110; - break zzForNext; - default: - break zzForAction; - } - - case 102: - switch (zzInput) { - case 19: - zzState = 111; - break zzForNext; - default: - break zzForAction; - } - - case 103: - switch (zzInput) { - case 18: - zzState = 112; - break zzForNext; - default: - break zzForAction; - } - - case 104: - switch (zzInput) { - case 21: - zzState = 113; - break zzForNext; - default: - break zzForAction; - } - - case 105: - switch (zzInput) { - case 14: - zzState = 114; - break zzForNext; - default: - break zzForAction; - } - - case 106: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzState = 115; - break zzForNext; - default: - break zzForAction; - } - - case 107: - switch (zzInput) { - case 37: - zzState = 116; - break zzForNext; - default: - break zzForAction; - } - - case 108: - switch (zzInput) { - case 38: - zzState = 117; - break zzForNext; - default: - break zzForAction; - } - - case 109: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 109; - break zzForNext; - case 7: - zzIsFinal = true; - zzState = 118; - break zzForNext; - default: - break zzForAction; - } - - case 110: - switch (zzInput) { - case 22: - zzState = 119; - break zzForNext; - default: - break zzForAction; - } - - case 111: - switch (zzInput) { - case 19: - zzState = 120; - break zzForNext; - default: - break zzForAction; - } - - case 112: - switch (zzInput) { - case 17: - zzState = 121; - break zzForNext; - default: - break zzForAction; - } - - case 113: - switch (zzInput) { - case 22: - zzState = 122; - break zzForNext; - default: - break zzForAction; - } - - case 114: - switch (zzInput) { - case 29: - zzState = 123; - break zzForNext; - default: - break zzForAction; - } - - case 115: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzState = 115; - break zzForNext; - default: - break zzForAction; - } - - case 116: - switch (zzInput) { - case 22: - zzState = 124; - break zzForNext; - default: - break zzForAction; - } - - case 117: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 117; - break zzForNext; - case 7: - zzIsFinal = true; - zzState = 125; - break zzForNext; - default: - break zzForAction; - } - - case 118: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzState = 118; - break zzForNext; - default: - break zzForAction; - } - - case 119: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 119; - break zzForNext; - case 7: - zzIsFinal = true; - zzState = 126; - break zzForNext; - default: - break zzForAction; - } - - case 120: - switch (zzInput) { - case 20: - zzState = 127; - break zzForNext; - default: - break zzForAction; - } - - case 121: - switch (zzInput) { - case 16: - zzState = 128; - break zzForNext; - default: - break zzForAction; - } - - case 122: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 122; - break zzForNext; - case 23: - zzState = 129; - break zzForNext; - case 34: - zzState = 130; - break zzForNext; - default: - break zzForAction; - } - - case 123: - switch (zzInput) { - case 30: - zzState = 131; - break zzForNext; - default: - break zzForAction; - } - - case 124: - switch (zzInput) { - case 18: - zzState = 132; - break zzForNext; - default: - break zzForAction; - } - - case 125: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzState = 125; - break zzForNext; - default: - break zzForAction; - } - - case 126: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzState = 126; - break zzForNext; - default: - break zzForAction; - } - - case 127: - switch (zzInput) { - case 21: - zzState = 133; - break zzForNext; - default: - break zzForAction; - } - - case 128: - switch (zzInput) { - case 26: - zzState = 134; - break zzForNext; - default: - break zzForAction; - } - - case 129: - switch (zzInput) { - case 19: - zzState = 135; - break zzForNext; - default: - break zzForAction; - } - - case 130: - switch (zzInput) { - case 13: - zzState = 136; - break zzForNext; - default: - break zzForAction; - } - - case 131: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 131; - break zzForNext; - case 7: - zzState = 137; - break zzForNext; - default: - break zzForAction; - } - - case 132: - switch (zzInput) { - case 19: - zzState = 138; - break zzForNext; - default: - break zzForAction; - } - - case 133: - switch (zzInput) { - case 22: - zzState = 139; - break zzForNext; - default: - break zzForAction; - } - - case 134: - switch (zzInput) { - case 29: - zzState = 140; - break zzForNext; - default: - break zzForAction; - } - - case 135: - switch (zzInput) { - case 13: - zzState = 141; - break zzForNext; - default: - break zzForAction; - } - - case 136: - switch (zzInput) { - case 14: - zzState = 142; - break zzForNext; - default: - break zzForAction; - } - - case 137: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 137; - break zzForNext; - case 31: - case 32: - zzState = 143; - break zzForNext; - default: - break zzForAction; - } - - case 138: - switch (zzInput) { - case 26: - zzState = 144; - break zzForNext; - default: - break zzForAction; - } - - case 139: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 139; - break zzForNext; - case 7: - zzIsFinal = true; - zzState = 145; - break zzForNext; - default: - break zzForAction; - } - - case 140: - switch (zzInput) { - case 38: - zzState = 146; - break zzForNext; - default: - break zzForAction; - } - - case 141: - switch (zzInput) { - case 14: - zzState = 147; - break zzForNext; - default: - break zzForAction; - } - - case 142: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 142; - break zzForNext; - case 21: - zzState = 148; - break zzForNext; - default: - break zzForAction; - } - - case 143: - switch (zzInput) { - case 23: - zzState = 149; - break zzForNext; - default: - break zzForAction; - } - - case 144: - switch (zzInput) { - case 45: - zzState = 150; - break zzForNext; - default: - break zzForAction; - } - - case 145: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzState = 145; - break zzForNext; - default: - break zzForAction; - } - - case 146: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 146; - break zzForNext; - case 7: - zzIsFinal = true; - zzState = 151; - break zzForNext; - default: - break zzForAction; - } - - case 147: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzState = 147; - break zzForNext; - case 21: - zzState = 152; - break zzForNext; - default: - break zzForAction; - } - - case 148: - switch (zzInput) { - case 24: - zzState = 153; - break zzForNext; - default: - break zzForAction; - } - - case 149: - switch (zzInput) { - case 19: - zzState = 154; - break zzForNext; - default: - break zzForAction; - } - - case 150: - switch (zzInput) { - case 22: - zzState = 155; - break zzForNext; - default: - break zzForAction; - } - - case 151: - switch (zzInput) { - case 6: - case 8: - case 9: - case 28: - zzIsFinal = true; - zzState = 151; - break zzForNext; - default: - break zzForAction; - } - - case 152: - switch (zzInput) { - case 24: - zzState = 156; - break zzForNext; - default: - break zzForAction; - } - - case 153: - switch (zzInput) { - case 25: - zzState = 157; - break zzForNext; - default: - break zzForAction; - } - - case 154: - switch (zzInput) { - case 19: - zzState = 158; - break zzForNext; - default: - break zzForAction; - } - - case 155: - switch (zzInput) { - case 35: - zzState = 159; - break zzForNext; - default: - break zzForAction; - } - - case 156: - switch (zzInput) { - case 25: - zzState = 160; - break zzForNext; - default: - break zzForAction; - } - - case 157: - switch (zzInput) { - case 14: - zzState = 161; - break zzForNext; - default: - break zzForAction; - } - - case 158: - switch (zzInput) { - case 21: - zzState = 162; - break zzForNext; - default: - break zzForAction; - } - - case 159: - switch (zzInput) { - case 21: - zzState = 76; - break zzForNext; - default: - break zzForAction; - } - - case 160: - switch (zzInput) { - case 14: - zzState = 163; - break zzForNext; - default: - break zzForAction; - } - - case 161: - switch (zzInput) { - case 26: - zzState = 164; - break zzForNext; - default: - break zzForAction; - } - - case 162: - switch (zzInput) { - case 33: - zzState = 165; - break zzForNext; - default: - break zzForAction; - } - - case 163: - switch (zzInput) { - case 26: - zzState = 166; - break zzForNext; - default: - break zzForAction; - } - - case 164: - switch (zzInput) { - case 18: - zzState = 167; - break zzForNext; - default: - break zzForAction; - } - - case 165: - switch (zzInput) { - case 27: - zzState = 168; - break zzForNext; - default: - break zzForAction; - } - - case 166: - switch (zzInput) { - case 18: - zzState = 169; - break zzForNext; - default: - break zzForAction; - } - - case 167: - switch (zzInput) { - case 27: - zzState = 170; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 167; - break zzForNext; - } - - case 168: - switch (zzInput) { - case 27: - zzState = 171; - break zzForNext; - default: - break zzForAction; - } - - case 169: - switch (zzInput) { - case 27: - zzState = 172; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 170: - switch (zzInput) { - case 27: - zzState = 173; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 167; - break zzForNext; - } - - case 171: - switch (zzInput) { - case 34: - zzState = 174; - break zzForNext; - default: - break zzForAction; - } - - case 172: - switch (zzInput) { - case 27: - zzState = 175; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 173: - switch (zzInput) { - case 27: - zzState = 173; - break zzForNext; - case 16: - zzState = 176; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 167; - break zzForNext; - } - - case 174: - switch (zzInput) { - case 34: - zzState = 177; - break zzForNext; - default: - break zzForAction; - } - - case 175: - switch (zzInput) { - case 27: - zzState = 175; - break zzForNext; - case 16: - zzState = 178; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 176: - switch (zzInput) { - case 27: - zzState = 170; - break zzForNext; - case 19: - zzState = 179; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 167; - break zzForNext; - } - - case 177: - switch (zzInput) { - case 34: - zzState = 180; - break zzForNext; - default: - break zzForAction; - } - - case 178: - switch (zzInput) { - case 27: - zzState = 172; - break zzForNext; - case 19: - zzState = 181; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 179: - switch (zzInput) { - case 27: - zzState = 170; - break zzForNext; - case 16: - zzState = 182; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 167; - break zzForNext; - } - - case 180: - switch (zzInput) { - case 35: - zzState = 183; - break zzForNext; - default: - break zzForAction; - } - - case 181: - switch (zzInput) { - case 27: - zzState = 172; - break zzForNext; - case 16: - zzState = 184; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 182: - switch (zzInput) { - case 27: - zzState = 170; - break zzForNext; - case 28: - zzState = 185; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 167; - break zzForNext; - } - - case 183: - switch (zzInput) { - case 34: - zzState = 186; - break zzForNext; - default: - break zzForAction; - } - - case 184: - switch (zzInput) { - case 27: - zzState = 172; - break zzForNext; - case 28: - zzState = 187; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 185: - switch (zzInput) { - case 27: - zzState = 170; - break zzForNext; - case 34: - zzState = 188; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 167; - break zzForNext; - } - - case 186: - switch (zzInput) { - case 36: - zzState = 189; - break zzForNext; - default: - break zzForAction; - } - - case 187: - switch (zzInput) { - case 27: - zzState = 172; - break zzForNext; - case 12: - zzState = 190; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 188: - switch (zzInput) { - case 27: - zzState = 170; - break zzForNext; - case 13: - zzState = 191; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 167; - break zzForNext; - } - - case 189: - switch (zzInput) { - case 35: - zzState = 192; - break zzForNext; - default: - break zzForAction; - } - - case 190: - switch (zzInput) { - case 27: - zzState = 172; - break zzForNext; - case 23: - zzState = 193; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 191: - switch (zzInput) { - case 27: - zzState = 170; - break zzForNext; - case 14: - zzIsFinal = true; - zzState = 194; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 167; - break zzForNext; - } - - case 192: - switch (zzInput) { - case 17: - zzState = 195; - break zzForNext; - default: - break zzForAction; - } - - case 193: - switch (zzInput) { - case 27: - zzState = 172; - break zzForNext; - case 19: - zzState = 196; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 194: - switch (zzInput) { - case 27: - zzState = 170; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 167; - break zzForNext; - } - - case 195: - switch (zzInput) { - case 37: - zzState = 197; - break zzForNext; - default: - break zzForAction; - } - - case 196: - switch (zzInput) { - case 27: - zzState = 172; - break zzForNext; - case 13: - zzState = 198; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 197: - switch (zzInput) { - case 38: - zzState = 199; - break zzForNext; - default: - break zzForAction; - } - - case 198: - switch (zzInput) { - case 27: - zzState = 172; - break zzForNext; - case 14: - zzIsFinal = true; - zzState = 200; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 199: - switch (zzInput) { - case 27: - zzState = 201; - break zzForNext; - default: - break zzForAction; - } - - case 200: - switch (zzInput) { - case 27: - zzState = 172; - break zzForNext; - case 9: - break zzForAction; - default: - zzState = 169; - break zzForNext; - } - - case 201: - switch (zzInput) { - case 39: - zzState = 202; - break zzForNext; - default: - break zzForAction; - } - - case 202: - switch (zzInput) { - case 40: - zzState = 203; - break zzForNext; - default: - break zzForAction; - } - - case 203: - switch (zzInput) { - case 40: - zzState = 204; - break zzForNext; - default: - break zzForAction; - } - - case 204: - switch (zzInput) { - case 40: - zzState = 205; - break zzForNext; - default: - break zzForAction; - } - - case 205: - switch (zzInput) { - case 27: - zzState = 206; - break zzForNext; - default: - break zzForAction; - } - - case 206: - switch (zzInput) { - case 12: - zzState = 207; - break zzForNext; - default: - break zzForAction; - } - - case 207: - switch (zzInput) { - case 23: - zzState = 208; - break zzForNext; - default: - break zzForAction; - } - - case 208: - switch (zzInput) { - case 19: - zzState = 209; - break zzForNext; - default: - break zzForAction; - } - - case 209: - switch (zzInput) { - case 13: - zzState = 210; - break zzForNext; - default: - break zzForAction; - } - - case 210: - switch (zzInput) { - case 14: - zzIsFinal = true; - zzNoLookAhead = true; - zzState = 211; - break zzForNext; - default: - break zzForAction; - } - - default: - // if this is ever reached, there is a serious bug - // in JFlex - zzScanError(JSPHeadTokenizer.ZZ_UNKNOWN_ERROR); - break; - } - } - - if (zzIsFinal) { - zzAction = zzState; - zzMarkedPosL = zzCurrentPosL; - if (zzNoLookAhead) { - break zzForAction; - } - } - - } - } - - // store back cached position - zzMarkedPos = zzMarkedPosL; - - switch (zzAction < 0 ? zzAction : JSPHeadTokenizer.ZZ_ACTION[zzAction]) { - case 10: { - if (yychar == 0) { - hasMore = false; - return EncodingParserConstants.UTF16BE; - } - } - case 27: - break; - case 17: { - if (yychar == 0) { - hasMore = false; - return EncodingParserConstants.UTF83ByteBOM; - } - } - case 28: - break; - case 4: { - yybegin(JSPHeadTokenizer.SQ_STRING); - string.setLength(0); - } - case 29: - break; - case 5: { - string.append(yytext()); - } - case 30: - break; - case 22: { - pushCurrentState(); - yybegin(JSPHeadTokenizer.QuotedAttributeValue); - return JSPHeadTokenizerConstants.PageLanguage; - } - case 31: - break; - case 26: { - isXHTML = true; - } - case 32: - break; - case 24: { - pushCurrentState(); - yybegin(JSPHeadTokenizer.QuotedAttributeValue); - return JSPHeadTokenizerConstants.PageEncoding; - } - case 33: - break; - case 1: { - if (yychar > JSPHeadTokenizer.MAX_TO_SCAN) { - hasMore = false; - return EncodingParserConstants.MAX_CHARS_REACHED; - } - } - case 34: - break; - case 11: { - if (yychar == 0) { - hasMore = false; - return EncodingParserConstants.UTF16LE; - } - } - case 35: - break; - case 6: { - yypushback(1); - popState(); - valueText = string.toString(); - return EncodingParserConstants.InvalidTerminatedStringValue; - } - case 36: - break; - case 8: { - yypushback(1); - popState(); - valueText = string.toString(); - return EncodingParserConstants.UnDelimitedStringValue; - } - case 37: - break; - case 9: { - yypushback(1); - popState(); - valueText = string.toString(); - return EncodingParserConstants.InvalidTermintatedUnDelimitedStringValue; - } - case 38: - break; - case 7: { - popState(); - valueText = string.toString(); - return EncodingParserConstants.StringValue; - } - case 39: - break; - case 14: { - yybegin(JSPHeadTokenizer.YYINITIAL); - return JSPHeadTokenizerConstants.PageDirectiveEnd; - } - case 40: - break; - case 23: { - pushCurrentState(); - yybegin(JSPHeadTokenizer.QuotedAttributeValue); - return JSPHeadTokenizerConstants.PageContentType; - } - case 41: - break; - case 18: { - if (yychar == 0) { - yybegin(JSPHeadTokenizer.ST_XMLDecl); - return XMLHeadTokenizerConstants.XMLDeclStart; - } - } - case 42: - break; - case 15: { - yypushback(2); - popState(); - valueText = string.toString(); - return EncodingParserConstants.InvalidTerminatedStringValue; - } - case 43: - break; - case 2: { - yypushback(1); - yybegin(JSPHeadTokenizer.UnDelimitedString); - string.setLength(0); - } - case 44: - break; - case 12: { - yybegin(JSPHeadTokenizer.YYINITIAL); - return XMLHeadTokenizerConstants.XMLDeclEnd; - } - case 45: - break; - case 13: { - yybegin(JSPHeadTokenizer.YYINITIAL); - return JSPHeadTokenizerConstants.PageDirectiveEnd; - } - case 46: - break; - case 25: { - isWML = true; - } - case 47: - break; - case 19: { - yybegin(JSPHeadTokenizer.ST_PAGE_DIRECTIVE); - return JSPHeadTokenizerConstants.PageDirectiveStart; - } - case 48: - break; - case 21: { - pushCurrentState(); - yybegin(JSPHeadTokenizer.QuotedAttributeValue); - return XMLHeadTokenizerConstants.XMLDelEncoding; - } - case 49: - break; - case 20: { - pushCurrentState(); - yybegin(JSPHeadTokenizer.QuotedAttributeValue); - return XMLHeadTokenizerConstants.XMLDeclVersion; - } - case 50: - break; - case 16: { - yypushback(2); - popState(); - valueText = string.toString(); - return EncodingParserConstants.InvalidTerminatedStringValue; - } - case 51: - break; - case 3: { - yybegin(JSPHeadTokenizer.DQ_STRING); - string.setLength(0); - } - case 52: - break; - default: - if (zzInput == JSPHeadTokenizer.YYEOF && zzStartRead == zzCurrentPos) { - zzAtEOF = true; - zzDoEOF(); - { - hasMore = false; - return EncodingParserConstants.EOF; - } - } else { - zzScanError(JSPHeadTokenizer.ZZ_NO_MATCH); - } - } - } - } - - private void pushCurrentState() { - fStateStack.push(yystate()); - - } - - public void reset(Reader in) { - /* the input device */ - zzReader = in; - - /* the current state of the DFA */ - zzState = 0; - - /* the current lexical state */ - zzLexicalState = JSPHeadTokenizer.YYINITIAL; - - /* - * this buffer contains the current text to be matched and is the source - * of the yytext() string - */ - java.util.Arrays.fill(zzBuffer, (char) 0); - - /* the textposition at the last accepting state */ - zzMarkedPos = 0; - - /* the textposition at the last state to be included in yytext */ - zzPushbackPos = 0; - - /* the current text position in the buffer */ - zzCurrentPos = 0; - - /* startRead marks the beginning of the yytext() string in the buffer */ - zzStartRead = 0; - - /** - * endRead marks the last character in the buffer, that has been read - * from input - */ - zzEndRead = 0; - - /* number of newlines encountered up to the start of the matched text */ - // yyline = 0; - /* the number of characters up to the start of the matched text */ - yychar = 0; - - /** - * the number of characters from the last newline up to the start of the - * matched text - */ - // yycolumn = 0; - /** - * yy_atBOL == true <=> the scanner is currently at the beginning of a - * line - */ - zzAtBOL = true; - - /* yy_atEOF == true <=> the scanner has returned a value for EOF */ - zzAtEOF = false; - - /* denotes if the user-EOF-code has already been executed */ - zzEOFDone = false; - - fStateStack.clear(); - - hasMore = true; - isXHTML = false; - isWML = false; - - } - - /** - * Enters a new lexical state - * - * @param newState - * the new lexical state - */ - public final void yybegin(int newState) { - zzLexicalState = newState; - } - - /** - * Returns the character at position <tt>pos</tt> from the matched text. - * - * It is equivalent to yytext().charAt(pos), but faster - * - * @param pos - * the position of the character to fetch. A value from 0 to - * yylength()-1. - * - * @return the character at position pos - */ - public final char yycharat(int pos) { - return zzBuffer[zzStartRead + pos]; - } - - /** - * Closes the input stream. - */ - public final void yyclose() throws java.io.IOException { - zzAtEOF = true; /* indicate end of file */ - zzEndRead = zzStartRead; /* invalidate buffer */ - - if (zzReader != null) { - zzReader.close(); - } - } - - /** - * Returns the length of the matched text region. - */ - public final int yylength() { - return zzMarkedPos - zzStartRead; - } - - /** - * Pushes the specified amount of characters back into the input stream. - * - * They will be read again by then next call of the scanning method - * - * @param number - * the number of characters to be read again. This number must - * not be greater than yylength()! - */ - public void yypushback(int number) { - if (number > yylength()) { - zzScanError(JSPHeadTokenizer.ZZ_PUSHBACK_2BIG); - } - - zzMarkedPos -= number; - } - - /** - * Resets the scanner to read from a new input stream. Does not close the - * old reader. - * - * All internal variables are reset, the old input stream <b>cannot</b> be - * reused (internal buffer is discarded and lost). Lexical state is set to - * <tt>ZZ_INITIAL</tt>. - * - * @param reader - * the new input stream - */ - public final void yyreset(java.io.Reader reader) { - zzReader = reader; - zzAtBOL = true; - zzAtEOF = false; - zzEndRead = zzStartRead = 0; - zzCurrentPos = zzMarkedPos = zzPushbackPos = 0; - // yyline = yychar = yycolumn = 0; - zzLexicalState = JSPHeadTokenizer.YYINITIAL; - } - - /** - * Returns the current lexical state. - */ - public final int yystate() { - return zzLexicalState; - } - - /** - * Returns the text matched by the current regular expression. - */ - public final String yytext() { - return new String(zzBuffer, zzStartRead, zzMarkedPos - zzStartRead); - } - - /** - * Contains user EOF-code, which will be executed exactly once, when the end - * of file is reached - */ - private void zzDoEOF() { - if (!zzEOFDone) { - zzEOFDone = true; - hasMore = false; - - } - } - - /** - * Refills the input buffer. - * - * @return <code>false</code>, iff there was new input. - * - * @exception java.io.IOException - * if any I/O-Error occurs - */ - private boolean zzRefill() throws java.io.IOException { - - /* first: make room (if you can) */ - if (zzStartRead > 0) { - System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead - zzStartRead); - - /* translate stored positions */ - zzEndRead -= zzStartRead; - zzCurrentPos -= zzStartRead; - zzMarkedPos -= zzStartRead; - zzPushbackPos -= zzStartRead; - zzStartRead = 0; - } - - /* is the buffer big enough? */ - if (zzCurrentPos >= zzBuffer.length) { - /* if not: blow it up */ - char newBuffer[] = new char[zzCurrentPos * 2]; - System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); - zzBuffer = newBuffer; - } - - /* finally: fill the buffer with new input */ - int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length - zzEndRead); - - if (numRead < 0) { - return true; - } else { - zzEndRead += numRead; - return false; - } - } - - /** - * Reports an error that occured while scanning. - * - * In a wellformed scanner (no or only correct usage of yypushback(int) and - * a match-all fallback rule) this method will only be called with things - * that "Can't Possibly Happen". If this method is called, something is - * seriously wrong (e.g. a JFlex bug producing a faulty scanner etc.). - * - * Usual syntax/scanner level error handling should be done in error - * fallback rules. - * - * @param errorCode - * the code of the errormessage to display - */ - private void zzScanError(int errorCode) { - String message; - try { - message = JSPHeadTokenizer.ZZ_ERROR_MSG[errorCode]; - } catch (ArrayIndexOutOfBoundsException e) { - message = JSPHeadTokenizer.ZZ_ERROR_MSG[JSPHeadTokenizer.ZZ_UNKNOWN_ERROR]; - } - - throw new Error(message); - } - -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/JSPHeadTokenizerConstants.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/JSPHeadTokenizerConstants.java deleted file mode 100644 index e823fd53dd..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/JSPHeadTokenizerConstants.java +++ /dev/null @@ -1,21 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.contenttype; - -import org.eclipse.wst.xml.core.internal.contenttype.XMLHeadTokenizerConstants; - -public interface JSPHeadTokenizerConstants extends XMLHeadTokenizerConstants { - String PageContentType = "PageContentType"; //$NON-NLS-1$ - String PageDirectiveEnd = "PageDirectiveEnd"; //$NON-NLS-1$ - String PageDirectiveStart = "PageDirectiveStart"; //$NON-NLS-1$ - String PageEncoding = "PageEncoding"; //$NON-NLS-1$ - String PageLanguage = "PageLanguage"; //$NON-NLS-1$ -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/JSPResourceEncodingDetector.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/JSPResourceEncodingDetector.java deleted file mode 100644 index 1fe640b063..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/contenttype/JSPResourceEncodingDetector.java +++ /dev/null @@ -1,505 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.contenttype; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.nio.charset.Charset; -import java.nio.charset.IllegalCharsetNameException; -import java.nio.charset.UnsupportedCharsetException; -import java.util.regex.Pattern; - -import org.eclipse.core.resources.IStorage; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.wst.sse.core.internal.encoding.CodedIO; -import org.eclipse.wst.sse.core.internal.encoding.EncodingMemento; -import org.eclipse.wst.sse.core.internal.encoding.IResourceCharsetDetector; -import org.eclipse.wst.sse.core.internal.encoding.NonContentBasedEncodingRules; -import org.eclipse.wst.xml.core.internal.contenttype.EncodingParserConstants; -import org.eclipse.wst.xml.core.internal.contenttype.XMLHeadTokenizerConstants; - -public class JSPResourceEncodingDetector implements IResourceCharsetDetector { - - class NullMemento extends EncodingMemento { - /** - * - */ - public NullMemento() { - super(); - String defaultCharset = NonContentBasedEncodingRules.useDefaultNameRules(null); - setJavaCharsetName(defaultCharset); - setAppropriateDefault(defaultCharset); - setDetectedCharsetName(null); - } - - } - - private String fCharset; - - private String fContentType; - - private String fContentTypeValue; - - private EncodingMemento fEncodingMemento; - - private boolean fHeaderParsed; - - private String fLanguage; - - private String fPageEncodingValue; - - private Reader fReader; - - private JSPHeadTokenizer fTokenizer; - - private boolean fWML; - - private boolean fXHTML; - - private String fXMLDecEncodingName; - - private boolean unicodeCase; - - /** - * No Arg constructor. - */ - public JSPResourceEncodingDetector() { - super(); - } - - private boolean canHandleAsUnicodeStream(String tokenType) { - boolean canHandleAsUnicode = false; - if (tokenType == EncodingParserConstants.UTF83ByteBOM) { - canHandleAsUnicode = true; - String enc = "UTF-8"; //$NON-NLS-1$ - createEncodingMemento(enc, EncodingMemento.DETECTED_STANDARD_UNICODE_BYTES); - fEncodingMemento.setUTF83ByteBOMUsed(true); - } else if (tokenType == EncodingParserConstants.UTF16BE) { - canHandleAsUnicode = true; - String enc = "UTF-16BE"; //$NON-NLS-1$ - createEncodingMemento(enc, EncodingMemento.DETECTED_STANDARD_UNICODE_BYTES); - } else if (tokenType == EncodingParserConstants.UTF16LE) { - canHandleAsUnicode = true; - String enc = "UTF-16"; //$NON-NLS-1$ - createEncodingMemento(enc, EncodingMemento.DETECTED_STANDARD_UNICODE_BYTES); - } - return canHandleAsUnicode; - } - - /** - * Note: once this instance is created, trace info still needs to be - * appended by caller, depending on the context its created. - */ - private void createEncodingMemento(String detectedCharsetName) { - fEncodingMemento = new EncodingMemento(); - fEncodingMemento.setJavaCharsetName(getAppropriateJavaCharset(detectedCharsetName)); - fEncodingMemento.setDetectedCharsetName(detectedCharsetName); - // TODO: if detectedCharset and spec default is - // null, need to use "work - // bench based" defaults. - fEncodingMemento.setAppropriateDefault(getSpecDefaultEncoding()); - } - - /** - * convience method all subclasses can use (but not override) - * - * @param detectedCharsetName - * @param reason - */ - private void createEncodingMemento(String detectedCharsetName, String reason) { - createEncodingMemento(detectedCharsetName); - } - - /** - * convience method all subclasses can use (but not override) - */ - private void ensureInputSet() { - if (fReader == null) { - throw new IllegalStateException("input must be set before use"); //$NON-NLS-1$ - } - } - - /** - * There can sometimes be mulitple 'encodings' specified in a file. This is - * an attempt to centralize the rules for deciding between them. Returns - * encoding according to priority: 1. XML Declaration 2. page directive - * pageEncoding name 3. page directive contentType charset name - */ - private String getAppropriateEncoding() { - String result = null; - if (fXMLDecEncodingName != null) { - result = fXMLDecEncodingName; - } else if (fPageEncodingValue != null) { - result = fPageEncodingValue; - } else if (fCharset != null) { - result = fCharset; - } - return result; - } - - /** - * This method can return null, if invalid charset name (in which case - * "appropriateDefault" should be used, if a name is really need for some - * "save anyway" cases). - * - * @param detectedCharsetName - * @return - */ - private String getAppropriateJavaCharset(String detectedCharsetName) { - String result = null; - // 1. Check explicit mapping overrides from - // property file -- its here we pick up "rules" for cases - // that are not even in Java - result = CodedIO.checkMappingOverrides(detectedCharsetName); - // 2. Use the "canonical" name from JRE mappings - // Note: see Charset JavaDoc, the name you get one - // with can be alias, - // the name you get back is "standard" name. - Charset javaCharset = null; - try { - javaCharset = Charset.forName(detectedCharsetName); - } catch (UnsupportedCharsetException e) { - // only set invalid, if result is same as detected -- they won't - // be equal if - // overridden - if (result != null && result.equals(detectedCharsetName)) { - fEncodingMemento.setInvalidEncoding(detectedCharsetName); - } - } catch (IllegalCharsetNameException e) { - // only set invalid, if result is same as detected -- they won't - // be equal if - // overridden - if (result != null && result.equals(detectedCharsetName)) { - fEncodingMemento.setInvalidEncoding(detectedCharsetName); - } - } - // give priority to java cononical name, if present - if (javaCharset != null) { - result = javaCharset.name(); - // but still allow overrides - result = CodedIO.checkMappingOverrides(result); - } - return result; - } - - /** - * @return Returns the contentType. - */ - public String getContentType() throws IOException { - ensureInputSet(); - if (!fHeaderParsed) { - parseInput(); - // we keep track of if header's already been parse, so can make - // multiple 'get' calls, without causing reparsing. - fHeaderParsed = true; - // Note: there is a "hidden assumption" here that an empty - // string in content should be treated same as not present. - } - return fContentType; - } - - public String getEncoding() throws IOException { - return getEncodingMemento().getDetectedCharsetName(); - } - - // to ensure consist overall rules used, we'll mark as - // final, - // and require subclasses to provide certain pieces of - // the - // implementation - public EncodingMemento getEncodingMemento() throws IOException { - ensureInputSet(); - if (!fHeaderParsed) { - parseInput(); - // we keep track of if header's already been - // parse, so can make - // multiple 'get' calls, without causing - // reparsing. - fHeaderParsed = true; - // Note: there is a "hidden assumption" here - // that an empty - // string in content should be treated same as - // not present. - } - if (fEncodingMemento == null) { - handleSpecDefault(); - } - if (fEncodingMemento == null) { - // safty net - fEncodingMemento = new NullMemento(); - } - return fEncodingMemento; - } - - public String getLanguage() throws IOException { - ensureInputSet(); - if (!fHeaderParsed) { - parseInput(); - fHeaderParsed = true; - } - return fLanguage; - } - - public String getSpecDefaultEncoding() { - // by JSP Spec - final String enc = "ISO-8859-1"; //$NON-NLS-1$ - return enc; - } - - public EncodingMemento getSpecDefaultEncodingMemento() { - resetAll(); - EncodingMemento result = null; - String enc = getSpecDefaultEncoding(); - if (enc != null) { - createEncodingMemento(enc, EncodingMemento.DEFAULTS_ASSUMED_FOR_EMPTY_INPUT); - fEncodingMemento.setAppropriateDefault(enc); - result = fEncodingMemento; - } - return result; - } - - private JSPHeadTokenizer getTokinizer() { - if (fTokenizer == null) { - fTokenizer = new JSPHeadTokenizer(); - } - return fTokenizer; - } - - private void handleSpecDefault() { - String encodingName; - encodingName = getSpecDefaultEncoding(); - if (encodingName != null) { - // createEncodingMemento(encodingName, - // EncodingMemento.USED_CONTENT_TYPE_DEFAULT); - fEncodingMemento = new EncodingMemento(); - fEncodingMemento.setJavaCharsetName(encodingName); - fEncodingMemento.setAppropriateDefault(encodingName); - } - } - - private boolean isLegalString(String valueTokenType) { - boolean result = false; - if (valueTokenType != null) { - result = valueTokenType.equals(EncodingParserConstants.StringValue) || valueTokenType.equals(EncodingParserConstants.UnDelimitedStringValue) || valueTokenType.equals(EncodingParserConstants.InvalidTerminatedStringValue) || valueTokenType.equals(EncodingParserConstants.InvalidTermintatedUnDelimitedStringValue); - } - return result; - } - - public boolean isWML() throws IOException { - ensureInputSet(); - if (!fHeaderParsed) { - parseInput(); - // we keep track of if header's already been parse, so can make - // multiple 'get' calls, without causing reparsing. - fHeaderParsed = true; - // Note: there is a "hidden assumption" here that an empty - // string in content should be treated same as not present. - } - return fWML; - } - - public boolean isXHTML() throws IOException { - ensureInputSet(); - if (!fHeaderParsed) { - parseInput(); - // we keep track of if header's already been parse, so can make - // multiple 'get' calls, without causing reparsing. - fHeaderParsed = true; - // Note: there is a "hidden assumption" here that an empty - // string in content should be treated same as not present. - } - return fXHTML; - } - - /** - * This method should be exactly the same as what is in - * JSPHeadTokenizerTester - * - * @param contentType - */ - private void parseContentTypeValue(String contentType) { - Pattern pattern = Pattern.compile(";\\s*charset\\s*=\\s*"); //$NON-NLS-1$ - String[] parts = pattern.split(contentType); - if (parts.length > 0) { - // if only one item, it can still be charset instead of - // contentType - if (parts.length == 1) { - if (parts[0].length() > 6) { - String checkForCharset = parts[0].substring(0, 7); - if (checkForCharset.equalsIgnoreCase("charset")) { //$NON-NLS-1$ - int eqpos = parts[0].indexOf('='); - eqpos = eqpos + 1; - if (eqpos < parts[0].length()) { - fCharset = parts[0].substring(eqpos); - fCharset = fCharset.trim(); - } - } else { - fContentType = parts[0]; - } - } - } else { - fContentType = parts[0]; - } - } - if (parts.length > 1) { - fCharset = parts[1]; - } - } - - /** - * Looks for what ever encoding properties the tokenizer returns. Its the - * responsibility of the tokenizer to stop when appropriate and not go too - * far. - */ - private void parseHeader(JSPHeadTokenizer tokenizer) throws IOException { - fPageEncodingValue = null; - fCharset = null; - - HeadParserToken token = null; - do { - // don't use 'get' here (at least until reset issue fixed) - token = tokenizer.getNextToken(); - String tokenType = token.getType(); - if (canHandleAsUnicodeStream(tokenType)) { - unicodeCase = true; - } else { - - if (tokenType == XMLHeadTokenizerConstants.XMLDelEncoding) { - if (tokenizer.hasMoreTokens()) { - HeadParserToken valueToken = tokenizer.getNextToken(); - String valueTokenType = valueToken.getType(); - if (isLegalString(valueTokenType)) { - fXMLDecEncodingName = valueToken.getText(); - } - } - } else if (tokenType == JSPHeadTokenizerConstants.PageEncoding) { - if (tokenizer.hasMoreTokens()) { - HeadParserToken valueToken = tokenizer.getNextToken(); - String valueTokenType = valueToken.getType(); - if (isLegalString(valueTokenType)) { - fPageEncodingValue = valueToken.getText(); - } - } - } else if (tokenType == JSPHeadTokenizerConstants.PageContentType) { - if (tokenizer.hasMoreTokens()) { - HeadParserToken valueToken = tokenizer.getNextToken(); - String valueTokenType = valueToken.getType(); - if (isLegalString(valueTokenType)) { - fContentTypeValue = valueToken.getText(); - } - } - } else if (tokenType == JSPHeadTokenizerConstants.PageLanguage) { - if (tokenizer.hasMoreTokens()) { - HeadParserToken valueToken = tokenizer.getNextToken(); - String valueTokenType = valueToken.getType(); - if (isLegalString(valueTokenType)) { - fLanguage = valueToken.getText(); - } - } - } - } - } while (tokenizer.hasMoreTokens()); - if (fContentTypeValue != null) { - parseContentTypeValue(fContentTypeValue); - } - if (tokenizer.isXHTML()) { - fXHTML = true; - } - if (tokenizer.isWML()) { - fWML = true; - } - - } - - private void parseInput() throws IOException { - JSPHeadTokenizer tokenizer = getTokinizer(); - fReader.reset(); - tokenizer.reset(fReader); - parseHeader(tokenizer); - // unicode stream cases are created directly in parseHeader - if (!unicodeCase) { - String enc = getAppropriateEncoding(); - if (enc != null && enc.length() > 0) { - createEncodingMemento(enc, EncodingMemento.FOUND_ENCODING_IN_CONTENT); - } - } - } - - /** - * - */ - private void resetAll() { - fReader = null; - fHeaderParsed = false; - fEncodingMemento = null; - fCharset = null; - fContentTypeValue = null; - fPageEncodingValue = null; - fXMLDecEncodingName = null; - unicodeCase = false; - fXHTML = false; - fWML = false; - } - - /** - * - */ - public void set(InputStream inputStream) { - resetAll(); - fReader = new ByteReader(inputStream); - try { - fReader.mark(CodedIO.MAX_MARK_SIZE); - } catch (IOException e) { - // impossible, since we know ByteReader - // supports marking - throw new Error(e); - } - } - - /** - * - */ - public void set(IStorage iStorage) throws CoreException { - resetAll(); - InputStream inputStream = iStorage.getContents(); - InputStream resettableStream = new BufferedInputStream(inputStream, CodedIO.MAX_BUF_SIZE); - resettableStream.mark(CodedIO.MAX_MARK_SIZE); - set(resettableStream); - // TODO we'll need to "remember" IFile, or - // get its (or its project's) settings, in case - // those are needed to handle cases when the - // encoding is not in the file stream. - } - - /** - * Note: this is not part of interface to help avoid confusion ... it - * expected this Reader is a well formed character reader ... that is, its - * all ready been determined to not be a unicode marked input stream. And, - * its assumed to be in the correct position, at position zero, ready to - * read first character. - */ - public void set(Reader reader) { - resetAll(); - fReader = reader; - if (!fReader.markSupported()) { - fReader = new BufferedReader(fReader); - } - try { - fReader.mark(CodedIO.MAX_MARK_SIZE); - } catch (IOException e) { - // impossble, since we just checked if markable - throw new Error(e); - } - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/encoding/IJSPHeadContentDetector.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/encoding/IJSPHeadContentDetector.java deleted file mode 100644 index 827d51a8b6..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/encoding/IJSPHeadContentDetector.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.encoding; - -import java.io.IOException; - -import org.eclipse.wst.sse.core.internal.document.IDocumentCharsetDetector; - -public interface IJSPHeadContentDetector extends IDocumentCharsetDetector { - String getContentType() throws IOException; - - String getLanguage() throws IOException; - -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/encoding/JSPDocumentHeadContentDetector.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/encoding/JSPDocumentHeadContentDetector.java deleted file mode 100644 index 2e74eb24f1..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/encoding/JSPDocumentHeadContentDetector.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.encoding; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.wst.jsdt.web.core.internal.contenttype.JSPResourceEncodingDetector; -import org.eclipse.wst.sse.core.internal.document.DocumentReader; - -/** - * This class parses beginning portion of JSP file to get attributes in page - * directiive - * - */ -public class JSPDocumentHeadContentDetector extends JSPResourceEncodingDetector implements IJSPHeadContentDetector { - - public JSPDocumentHeadContentDetector() { - super(); - } - - public void set(IDocument document) { - set(new DocumentReader(document, 0)); - - } - -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/CompilationUnitHelper.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/CompilationUnitHelper.java deleted file mode 100644 index 7a31ee2e3e..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/CompilationUnitHelper.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.eclipse.wst.jsdt.web.core.internal.java; - -import org.eclipse.wst.jsdt.core.WorkingCopyOwner; - -/** - * To ensure there is only one instance of ProblemRequestor and WorkingCopyOwner - * for JSP plugins. These were removed from JSPTranslation to ensure that the - * JSPTranslation was not held in memory by any type of JDT lists (caching - * search results, etc...) - * - * @author pavery - */ -public class CompilationUnitHelper { - - private static CompilationUnitHelper instance; - - public synchronized static final CompilationUnitHelper getInstance() { - - if (CompilationUnitHelper.instance == null) { - CompilationUnitHelper.instance = new CompilationUnitHelper(); - } - return CompilationUnitHelper.instance; - } - - private JSPProblemRequestor fProblemRequestor = null; - - private WorkingCopyOwner fWorkingCopyOwner = null; - - private CompilationUnitHelper() { - // force use of instance - } - - public JSPProblemRequestor getProblemRequestor() { - - if (fProblemRequestor == null) { - fProblemRequestor = new JSPProblemRequestor(); - } - return fProblemRequestor; - } - - public WorkingCopyOwner getWorkingCopyOwner() { - - if (fWorkingCopyOwner == null) { - fWorkingCopyOwner = new WorkingCopyOwner() { - @Override - public String toString() { - return "JSP Working copy owner"; //$NON-NLS-1$ - } - }; - } - return fWorkingCopyOwner; - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/EscapedTextUtil.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/EscapedTextUtil.java deleted file mode 100644 index ba1d552f72..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/EscapedTextUtil.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java; - -import java.util.Properties; - -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; - -import com.ibm.icu.util.StringTokenizer; - -/** - * class to handle chunks of text/regions with escaped character data - * - * @author pavery - */ -public class EscapedTextUtil { - - public static Properties fXMLtoJavaLookup = null; - - /** - * @return unescaped full text of that region, "" if there is no text - */ - public static String getUnescapedText(IStructuredDocumentRegion parent, ITextRegion r) { - String test = (parent != r) ? parent.getFullText(r) : parent.getFullText(); - return EscapedTextUtil.getUnescapedText(test); - } - - public static String getUnescapedText(String test) { - EscapedTextUtil.initLookup(); - StringBuffer buffer = new StringBuffer(); - if (test != null) { - StringTokenizer st = new StringTokenizer(test, "&;", true); //$NON-NLS-1$ - String tok1, tok2, tok3, transString; - while (st.hasMoreTokens()) { - tok1 = tok2 = tok3 = transString = ""; //$NON-NLS-1$ - tok1 = st.nextToken(); - if (tok1.equals("&") && st.hasMoreTokens()) //$NON-NLS-1$ - { - tok2 = st.nextToken(); - if (st.hasMoreTokens()) { - tok3 = st.nextToken(); - } - } - if (!(transString = EscapedTextUtil.fXMLtoJavaLookup.getProperty(tok1 + tok2 + tok3, "")).equals("")) //$NON-NLS-2$ //$NON-NLS-1$ - { - buffer.append(transString); - } else { - buffer.append(tok1 + tok2 + tok3); - } - } - return buffer.toString(); - } - return ""; //$NON-NLS-1$ - } - - /** - * initialize lookup tables - */ - private static void initLookup() { - EscapedTextUtil.fXMLtoJavaLookup = new Properties(); - EscapedTextUtil.fXMLtoJavaLookup.setProperty("'", "'"); //$NON-NLS-2$ //$NON-NLS-1$ - EscapedTextUtil.fXMLtoJavaLookup.setProperty(""", "\""); //$NON-NLS-2$ //$NON-NLS-1$ - EscapedTextUtil.fXMLtoJavaLookup.setProperty("&", "&"); //$NON-NLS-2$ //$NON-NLS-1$ - EscapedTextUtil.fXMLtoJavaLookup.setProperty("<", "<"); //$NON-NLS-2$ //$NON-NLS-1$ - EscapedTextUtil.fXMLtoJavaLookup.setProperty(">", ">"); //$NON-NLS-2$ //$NON-NLS-1$ - EscapedTextUtil.fXMLtoJavaLookup.setProperty(" ", " "); //$NON-NLS-2$ //$NON-NLS-1$ - } - - /** - * Get the String representation of an entity reference. - */ - public static String translateEntityReference(String entity) { - return EscapedTextUtil.fXMLtoJavaLookup.getProperty(entity, entity); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/IJSPTranslation.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/IJSPTranslation.java deleted file mode 100644 index 7110437009..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/IJSPTranslation.java +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java; - -import java.util.List; - -import org.eclipse.wst.jsdt.core.ICompilationUnit; -import org.eclipse.wst.jsdt.core.IJavaElement; - -/** - * An object that holds a translated JSP String along with position mapping from - * Java to JSP, and JSP to Java. - * - * @author pavery - * - */ -public interface IJSPTranslation { - - /** - * The corresponding CompilationUnit for the translated JSP document - * - * @return an ICompilationUnit of the translation - */ - public ICompilationUnit getCompilationUnit(); - - /** - * Returns the IJavaElements corresponding to the JSP range in the JSP - * StructuredDocument - * - * @param jspStart - * staring offset in the JSP document - * @param jspEnd - * ending offset in the JSP document - * @return IJavaElements corresponding to the JSP selection - */ - public IJavaElement[] getElementsFromJspRange(int jspStart, int jspEnd); - - /** - * The corresponding java offset in the translated document for a given jsp - * offset. - * - * @param jspPosition - * @return the java offset that maps to jspOffset, -1 if the position has no - * mapping. - */ - public int getJavaOffset(int jspOffset); - - /** - * The string contents of the translated document. - * - * @return the string contents of the translated document. - */ - public String getJavaText(); - - /** - * The corresponding jsp offset in the source document for a given jsp - * offset in the translated document. - * - * @param javaPosition - * @return the jsp offset that maps to javaOffset, -1 if the position has no - * mapping. - */ - public int getJspOffset(int javaOffset); - - /** - * @return the List of problems collected during reconcile of the - * compilation unit - */ - public List getProblems(); - - /** - * Reconciles the compilation unit for this JSPTranslation - */ - public void reconcileCompilationUnit(); - - /** - * Must be set true in order for problems to be collected during reconcile. - * If set false, problems will be ignored during reconcile. - * - * @param collect - */ - public void setProblemCollectingActive(boolean collect); - - // add these API once finalized - // getJspEdits(TextEdit javaEdit) - // getJavaRanges() - // getJavaDocument() -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSP2ServletNameUtil.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSP2ServletNameUtil.java deleted file mode 100644 index b5d664969b..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSP2ServletNameUtil.java +++ /dev/null @@ -1,140 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java; - -import java.io.File; - -/** - * @author pavery - */ -public class JSP2ServletNameUtil { - - /** - * Determine if given string is a valid Hex representation of an ASCII - * character (eg. 2F -> /) - * - * @param possible - * @return - */ - private static boolean isValid(String possible) { - boolean result = false; - if (possible.length() == 2) { - char c1 = possible.charAt(0); - char c2 = possible.charAt(1); - // 1st character must be a digit - if (Character.isDigit(c1)) { - // 2nd character must be digit or upper case letter A-F - if (Character.isDigit(c2)) { - result = true; - } else if (Character.isUpperCase(c2) && (c2 == 'A' || c2 == 'B' || c2 == 'C' || c2 == 'D' || c2 == 'E' || c2 == 'F')) { - result = true; - } - } - } - return result; - } - - /** - * Mangle string to WAS-like specifications - * - */ - public final static String mangle(String name) { - StringBuffer modifiedName = new StringBuffer(); - - // extension (.jsp, .jspf, .jspx, etc...) should already be encoded in - // name - - int length = name.length(); - // in case name is forbidden (a number, class, for, etc...) - modifiedName.append('_'); - - // ensure rest of characters are valid - for (int i = 0; i < length; i++) { - char currentChar = name.charAt(i); - if (Character.isJavaIdentifierPart(currentChar) == true) { - modifiedName.append(currentChar); - } else { - modifiedName.append(JSP2ServletNameUtil.mangleChar(currentChar)); - } - } - return modifiedName.toString(); - - } - - /** - * take a character and return its hex equivalent - */ - private final static String mangleChar(char ch) { - if (ch == File.separatorChar) { - ch = '/'; - } - - if (Character.isLetterOrDigit(ch) == true) { - return "" + ch; //$NON-NLS-1$ - } - return "_" + Integer.toHexString(ch).toUpperCase() + "_"; //$NON-NLS-1$ //$NON-NLS-2$ - } - - /** - * WAS mangles Tom&Jerry as: _Tom_26_Jerry; this takes in the mangled name - * and returns the original name. - * - * Unmangles the qualified type name. If an underscore is found it is - * assumed to be a mangled representation of a non-alpha, non-digit - * character of the form _NN_, where NN are hex digits representing the - * encoded character. This routine converts it back to the original - * character. - */ - public final static String unmangle(String qualifiedTypeName) { - if (qualifiedTypeName.charAt(0) != '_') { - return qualifiedTypeName; - } - - StringBuffer buf = new StringBuffer(); - String possible = ""; //$NON-NLS-1$ - - // remove the .java extension if there is one - if (qualifiedTypeName.endsWith(".java")) { - qualifiedTypeName = qualifiedTypeName.substring(0, qualifiedTypeName.length() - 5); - } - - for (int i = 1; i < qualifiedTypeName.length(); i++) { // start at - // index 1 b/c - // 1st char is - // always '_' - char c = qualifiedTypeName.charAt(i); - if (c == '_') { - int endIndex = qualifiedTypeName.indexOf('_', i + 1); - if (endIndex == -1) { - buf.append(c); - } else { - char unmangled; - try { - possible = qualifiedTypeName.substring(i + 1, endIndex); - if (JSP2ServletNameUtil.isValid(possible)) { - unmangled = (char) Integer.decode("0x" + possible).intValue();//$NON-NLS-1$ - i = endIndex; - } else { - unmangled = c; - } - - } catch (NumberFormatException e) { - unmangled = c; - } - buf.append(unmangled); - } - } else { - buf.append(c); - } - } - return buf.toString(); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPProblemRequestor.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPProblemRequestor.java deleted file mode 100644 index 6e5b520c48..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPProblemRequestor.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.eclipse.wst.jsdt.web.core.internal.java; - -/** - * @author pavery - */ - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.wst.jsdt.core.IProblemRequestor; -import org.eclipse.wst.jsdt.core.compiler.IProblem; - -class JSPProblemRequestor implements IProblemRequestor { - - private List fCollectedProblems; - - private boolean fIsActive = false; - - private boolean fIsRunning = false; - - public void acceptProblem(IProblem problem) { - - if (isActive()) { - fCollectedProblems.add(problem); - } - } - - public void beginReporting() { - - fIsRunning = true; - fCollectedProblems = new ArrayList(); - } - - public void endReporting() { - - fIsRunning = false; - } - - /** - * @return the list of collected problems - */ - public List getCollectedProblems() { - - return fCollectedProblems; - } - - public boolean isActive() { - - return fIsActive && fCollectedProblems != null; - } - - public boolean isRunning() { - - return fIsRunning; - } - - /** - * Sets the active state of this problem requestor. - * - * @param isActive - * the state of this problem requestor - */ - public void setIsActive(boolean isActive) { - - if (fIsActive != isActive) { - fIsActive = isActive; - if (fIsActive) { - startCollectingProblems(); - } else { - stopCollectingProblems(); - } - } - } - - /** - * Tells this annotation model to collect temporary problems from now on. - */ - private void startCollectingProblems() { - - fCollectedProblems = new ArrayList(); - } - - /** - * Tells this annotation model to no longer collect temporary problems. - */ - private void stopCollectingProblems() { - - // do nothing - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslation.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslation.java deleted file mode 100644 index f8af84051c..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslation.java +++ /dev/null @@ -1,761 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.text.Position; -import org.eclipse.wst.jsdt.core.IBuffer; -import org.eclipse.wst.jsdt.core.ICompilationUnit; -import org.eclipse.wst.jsdt.core.IJavaElement; -import org.eclipse.wst.jsdt.core.IJavaProject; -import org.eclipse.wst.jsdt.core.IPackageDeclaration; -import org.eclipse.wst.jsdt.core.IPackageFragment; -import org.eclipse.wst.jsdt.core.IPackageFragmentRoot; -import org.eclipse.wst.jsdt.core.ISourceRange; -import org.eclipse.wst.jsdt.core.JavaModelException; -import org.eclipse.wst.jsdt.core.WorkingCopyOwner; -import org.eclipse.wst.jsdt.internal.core.SourceRefElement; -import org.eclipse.wst.jsdt.ui.StandardJavaElementContentProvider; -import org.eclipse.wst.jsdt.web.core.internal.Logger; - -/** - * <p> - * An implementation of IJSPTranslation. <br> - * This object that holds the java translation of a JSP file as well as a - * mapping of ranges from the translated Java to the JSP source, and mapping - * from JSP source back to the translated Java. - * </p> - * - * <p> - * You may also use JSPTranslation to do CompilationUnit-esque things such as: - * <ul> - * <li>code select (get java elements for jsp selection)</li> - * <li>reconcile</li> - * <li>get java regions for jsp selection</li> - * <li>get a JSP text edit based on a Java text edit</li> - * <li>determine if a java offset falls within a jsp:useBean range</li> - * <li>determine if a java offset falls within a jsp import statment</li> - * </ul> - * </p> - * - * @author pavery - */ -public class JSPTranslation implements IJSPTranslation { - - // for debugging - private static final boolean DEBUG; - private static StandardJavaElementContentProvider fStandardJavaElementContentProvider; - - static { - String value = Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jsptranslation"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - public static StandardJavaElementContentProvider getElementProvider() { - if (JSPTranslation.fStandardJavaElementContentProvider == null) { - JSPTranslation.fStandardJavaElementContentProvider = new StandardJavaElementContentProvider(); - } - return JSPTranslation.fStandardJavaElementContentProvider; - } - - /** the name of the class (w/out extension) * */ - private String fClassname = ""; //$NON-NLS-1$ - private ICompilationUnit fCompilationUnit = null; - private List fGeneratedFunctionNames = null; - private HashMap fJava2JspImportsMap = null; - private HashMap fJava2JspMap = null; - private IJavaProject fJavaProject = null; - - private String fJavaText = ""; //$NON-NLS-1$ - private HashMap fJsp2JavaMap = null; - private String fJspName; - private String fJspText = ""; //$NON-NLS-1$ - /** lock to synchronize access to the compilation unit * */ - private byte[] fLock = null; - private String fMangledName; - - private IProgressMonitor fProgressMonitor = null; - - public JSPTranslation(IJavaProject javaProj, JSPTranslator translator) { - - fLock = new byte[0]; - fJavaProject = javaProj; - if (translator != null) { - fJavaText = translator.getTranslation().toString(); - fJspText = translator.getJspText(); - fClassname = translator.getClassname(); - fJava2JspMap = translator.getJava2JspRanges(); - fJsp2JavaMap = translator.getJsp2JavaRanges(); - fJava2JspImportsMap = translator.getJava2JspImportRanges(); - fGeneratedFunctionNames = translator.getFakeFunctionNames(); - - // fJava2JspIndirectMap = translator.getJava2JspIndirectRanges(); - } - } - - /** - * Originally from ReconcileStepForJava. Creates an ICompilationUnit from - * the contents of the JSP document. - * - * @return an ICompilationUnit from the contents of the JSP document - */ - private ICompilationUnit createCompilationUnit() throws JavaModelException { - - IPackageFragment packageFragment = null; - IJavaElement je = getJavaProject(); - - if (je == null || !je.exists()) { - return null; - } - - switch (je.getElementType()) { - case IJavaElement.PACKAGE_FRAGMENT: - je = je.getParent(); - // fall through - - case IJavaElement.PACKAGE_FRAGMENT_ROOT: - IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) je; - packageFragment = packageFragmentRoot.getPackageFragment(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH); - break; - - case IJavaElement.JAVA_PROJECT: - IJavaProject jProject = (IJavaProject) je; - - if (!jProject.exists()) { - if (JSPTranslation.DEBUG) { - System.out.println("** Abort create working copy: cannot create working copy: JSP is not in a Java project"); //$NON-NLS-1$ - } - return null; - } - - // packageFragmentRoot = null; - // packageFragmentRoot=JavaModelUtil.getPackageFragmentRoot(jProject); - // IPackageFragmentRoot[] packageFragmentRoots = - // jProject.getPackageFragmentRoots(); - packageFragmentRoot = jProject.getPackageFragmentRoot(jProject.getUnderlyingResource()); - if (packageFragmentRoot instanceof ICompilationUnit) { - return (ICompilationUnit) packageFragmentRoot; - } - - /* - * int i = 0; while (i < packageFragmentRoots.length) { if - * (!packageFragmentRoots[i].isArchive() && - * !packageFragmentRoots[i].isExternal() ) { packageFragmentRoot = - * packageFragmentRoots[i]; System.out.println("Accepting package - * fragment root:" + packageFragmentRoots[i].getElementName()); - * System.out.println("this is fragment number" + i + " out of - * "+packageFragmentRoots.length ); break; } i++; } - */ - if (packageFragmentRoot == null) { - if (JSPTranslation.DEBUG) { - System.out.println("** Abort create working copy: cannot create working copy: JSP is not in a Java project with source package fragment root"); //$NON-NLS-1$ - } - return null; - } - - /* - * for(int j =0; j<packageFragmentRoots.length;j++){ - * System.out.println(packageFragmentRoots[j].getElementName());; } - */ - - packageFragment = packageFragmentRoot.getPackageFragment(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH); - - break; - - default: - return null; - } - - // JavaModelManager.createCompilationUnitFrom(file, project) - - ICompilationUnit cu = packageFragment.getCompilationUnit(getClassname() + JsDataTypes.BASE_FILE_EXTENSION).getWorkingCopy(getWorkingCopyOwner(), getProblemRequestor(), getProgressMonitor()); - - setContents(cu); - // cu.makeConsistent(getProgressMonitor()); - // cu.reconcile(ICompilationUnit.NO_AST, true, getWorkingCopyOwner(), - // getProgressMonitor()); - - if (JSPTranslation.DEBUG) { - String cuText = cu.toString(); - System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); //$NON-NLS-1$ - System.out.println("(+) JSPTranslation [" + this + "] finished creating CompilationUnit: " + cu); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); //$NON-NLS-1$ - IPackageDeclaration[] ipd = cu.getPackageDeclarations(); - for (int i = 0; i < ipd.length; i++) { - System.out.println("JSPTranslation.getCU() Package:" + ipd[i].getElementName()); - } - - } - if (getJspName() == null || getMangledName() == null) { - String cuName = cu.getPath().lastSegment(); - if (cuName != null) { - setMangledName(cuName.substring(0, cuName.lastIndexOf('.'))); - // set name of jsp file - String unmangled = JSP2ServletNameUtil.unmangle(cuName); - setJspName(unmangled.substring(unmangled.lastIndexOf('/') + 1, unmangled.lastIndexOf('.'))); - } - } - return cu; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#fixupMangledName(java.lang.String) - */ - public String fixupMangledName(String displayString) { - - if (displayString == null) { - return null; - } - - return displayString.replaceAll(getMangledName(), getJspName()); - } - - public IJavaElement[] getAllElementsFromJspRange(int jspStart, int jspEnd) { - - int javaPositionStart = getJavaOffset(jspStart); - int javaPositionEnd = getJavaOffset(jspEnd); - - IJavaElement[] EMTPY_RESULT_SET = new IJavaElement[0]; - IJavaElement[] result = EMTPY_RESULT_SET; - - ICompilationUnit cu = getCompilationUnit(); - IJavaElement[] allChildren = null; - synchronized (cu) { - try { - allChildren = cu.getChildren(); - } catch (JavaModelException e) { - } - } - - Vector validChildren = new Vector(); - - for (int i = 0; i < allChildren.length; i++) { - if (allChildren[i] instanceof IJavaElement && allChildren[i].getElementType() != IJavaElement.PACKAGE_DECLARATION) { - ISourceRange range = getJSSourceRangeOf(allChildren[i]); - if (javaPositionStart <= range.getOffset() && range.getLength() + range.getOffset() <= (javaPositionEnd)) { - // if(precise && range.getOffset()>=javaPo && - // range.getLength()+range.getOffset() <= - // (javaPositionEnd)){ - validChildren.add(allChildren[i]); - // }else if(!precise && range.getOffset()<=javaPositionStart - // && ((range.getOffset() + range.getLength())>= - // javaPositionEnd)){ - // validChildren.add(allChildren[i]); - } - } - } - if (validChildren.size() > 0) { - result = (IJavaElement[]) validChildren.toArray(new IJavaElement[] {}); - } - - if (result == null || result.length == 0) { - return EMTPY_RESULT_SET; - } - - return result; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getClassname() - */ - public String getClassname() { - return fClassname; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getCompilationUnit() - */ - public ICompilationUnit getCompilationUnit() { - synchronized (fLock) { - try { - if (fCompilationUnit == null) { - fCompilationUnit = createCompilationUnit(); - } - reconcileCompilationUnit(); - } catch (JavaModelException jme) { - if (JSPTranslation.DEBUG) { - Logger.logException("error creating JSP working copy... ", jme); //$NON-NLS-1$ - } - } - - } - return fCompilationUnit; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getElementsFromJspRange(int, - * int) - */ - public IJavaElement[] getElementsFromJspRange(int jspStart, int jspEnd) { - - int javaPositionStart = getJavaOffset(jspStart); - int javaPositionEnd = getJavaOffset(jspEnd); - - IJavaElement[] EMTPY_RESULT_SET = new IJavaElement[0]; - IJavaElement[] result = EMTPY_RESULT_SET; - try { - ICompilationUnit cu = getCompilationUnit(); - // cu.makeConsistent(getProgressMonitor()); - // cu.reconcile(ICompilationUnit.NO_AST, true, - // getWorkingCopyOwner(), getProgressMonitor()); - if (cu != null) { - synchronized (cu) { - int cuDocLength = cu.getBuffer().getLength(); - int javaLength = javaPositionEnd - javaPositionStart; - if (cuDocLength > 0 && javaPositionStart >= 0 && javaLength >= 0 && javaPositionEnd <= cuDocLength) { - - result = cu.codeSelect(javaPositionStart, javaLength, getWorkingCopyOwner()); - - } - } - } - - if (result == null || result.length == 0) { - return EMTPY_RESULT_SET; - } - } catch (JavaModelException x) { - Logger.logException(x); - } - - return result; - } - - public List getGeneratedFunctionNames() { - return fGeneratedFunctionNames; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getJava2JspMap() - */ - public HashMap getJava2JspMap() { - return fJava2JspMap; - } - - public IJavaElement getJavaElementAtOffset(int htmlstart) { - IJavaElement elements = null; - int jsOffset = getJavaOffset(htmlstart); - // Position[] positions = getJavaRanges(htmlOffset, length); - // - ICompilationUnit cu = getCompilationUnit(); - synchronized (cu) { - try { - elements = cu.getElementAt(jsOffset); - } catch (JavaModelException e) { - // TODO Auto-generated catch block - if (JSPTranslation.DEBUG) { - Logger.logException("error retrieving java elemtnt from compilation unit... ", e); //$NON-NLS-1$ - } - } - } - return elements; - - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getJavaOffset(int) - */ - public int getJavaOffset(int jspOffset) { - int result = -1; - int offsetInRange = 0; - Position jspPos, javaPos = null; - - // iterate all mapped jsp ranges - Iterator it = fJsp2JavaMap.keySet().iterator(); - while (it.hasNext()) { - jspPos = (Position) it.next(); - // need to count the last position as included - if (!jspPos.includes(jspOffset) && !(jspPos.offset + jspPos.length == jspOffset)) { - continue; - } - - offsetInRange = jspOffset - jspPos.offset; - javaPos = (Position) fJsp2JavaMap.get(jspPos); - if (javaPos != null) { - result = javaPos.offset + offsetInRange; - } else { - - Logger.log(Logger.ERROR, "JavaPosition was null!" + jspOffset); //$NON-NLS-1$ - } - break; - } - return result; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#isUseBean(int) - */ - // public boolean isUseBean(int javaOffset) { - // System.out.println("REMOVE JSPTranslation.isUseBean(int javaOffset)"); - // return false; - // } - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getJavaPath() - */ - public String getJavaPath() { - // create if necessary - ICompilationUnit cu = getCompilationUnit(); - return (cu != null) ? cu.getPath().toString() : ""; //$NON-NLS-1$ - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getJavaProject() - */ - public IJavaProject getJavaProject() { - return fJavaProject; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getJavaRanges(int, - * int) - */ - public Position[] getJavaRanges(int offset, int length) { - - List results = new ArrayList(); - Iterator it = getJava2JspMap().keySet().iterator(); - Position p = null; - while (it.hasNext()) { - p = (Position) it.next(); - if (p.overlapsWith(offset, length)) { - results.add(p); - } - } - return (Position[]) results.toArray(new Position[results.size()]); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.IJSPTranslation#getJavaText() - */ - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getJavaText() - */ - public String getJavaText() { - - // return (fTranslator != null) ? - // fTranslator.getTranslation().toString(): ""; //$NON-NLS-1$ - - return fJavaText; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getJsp2JavaMap() - */ - public HashMap getJsp2JavaMap() { - return fJsp2JavaMap; - } - - private String getJspName() { - return fJspName; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getJspOffset(int) - */ - public int getJspOffset(int javaOffset) { - int result = -1; - int offsetInRange = 0; - Position jspPos, javaPos = null; - - // iterate all mapped java ranges - Iterator it = fJava2JspMap.keySet().iterator(); - while (it.hasNext()) { - javaPos = (Position) it.next(); - // need to count the last position as included - if (!javaPos.includes(javaOffset) && !(javaPos.offset + javaPos.length == javaOffset)) { - continue; - } - - offsetInRange = javaOffset - javaPos.offset; - jspPos = (Position) fJava2JspMap.get(javaPos); - - if (jspPos != null) { - result = jspPos.offset + offsetInRange; - } else { - Logger.log(Logger.ERROR, "jspPosition was null!" + javaOffset); //$NON-NLS-1$ - } - break; - } - - return result; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getJspText() - */ - public String getJspText() { - // return (fTranslator != null) ? fTranslator.getJspText() : ""; - // //$NON-NLS-1$ - // System.out.println("JSPTranslation.getJspText():\n" + fJspText + - // "-----------"); - return fJspText; - } - - private ISourceRange getJSSourceRangeOf(IJavaElement element) { - // returns the offset in html of given element - - ISourceRange range = null; - if (element instanceof SourceRefElement) { - try { - range = ((SourceRefElement) element).getSourceRange(); - } catch (JavaModelException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - return range; - } - - private String getMangledName() { - return fMangledName; - } - - /** - * - * @return the problem requestor for the CompilationUnit in this - * JSPTranslation - */ - private JSPProblemRequestor getProblemRequestor() { - return CompilationUnitHelper.getInstance().getProblemRequestor(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getProblems() - */ - public List getProblems() { - List problems = getProblemRequestor().getCollectedProblems(); - return problems != null ? problems : new ArrayList(); - } - - /** - * - * @return the progress monitor used in long operations (reconcile, creating - * the CompilationUnit...) in this JSPTranslation - */ - private IProgressMonitor getProgressMonitor() { - if (fProgressMonitor == null) { - fProgressMonitor = new NullProgressMonitor(); - } - return fProgressMonitor; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#getWorkingCopyOwner() - */ - public WorkingCopyOwner getWorkingCopyOwner() { - return CompilationUnitHelper.getInstance().getWorkingCopyOwner(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#isImport(int) - */ - public boolean isImport(int javaOffset) { - return isInRanges(javaOffset, fJava2JspImportsMap); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#isIndirect(int) - */ - public boolean isIndirect(int javaOffset) { - System.out.println("IMPLEMENT JSPTranslation.isIndirect(int javaOffset)"); - return false; - // return isInRanges(javaOffset, fJava2JspIndirectMap, false); - } - - private boolean isInRanges(int javaOffset, HashMap ranges) { - return isInRanges(javaOffset, ranges, true); - } - - /** - * Tells you if the given offset is included in any of the ranges - * (Positions) passed in. includeEndOffset tells whether or not to include - * the end offset of each range in the test. - * - * @param javaOffset - * @param ranges - * @param includeEndOffset - * @return - */ - private boolean isInRanges(int javaOffset, HashMap ranges, boolean includeEndOffset) { - - Iterator it = ranges.keySet().iterator(); - while (it.hasNext()) { - Position javaPos = (Position) it.next(); - // also include the start and end offset (only if requested) - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=81687 - if (javaPos.includes(javaOffset) || (includeEndOffset && javaPos.offset + javaPos.length == javaOffset)) { - return true; - } - } - return false; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#javaSpansMultipleJspPartitions(int, - * int) - */ - public boolean javaSpansMultipleJspPartitions(int javaOffset, int javaLength) { - HashMap java2jsp = getJava2JspMap(); - int count = 0; - Iterator it = java2jsp.keySet().iterator(); - Position javaRange = null; - while (it.hasNext()) { - javaRange = (Position) it.next(); - if (javaRange.overlapsWith(javaOffset, javaLength)) { - count++; - } - if (count > 1) { - return true; - } - } - return false; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#reconcileCompilationUnit() - */ - public void reconcileCompilationUnit() { - ICompilationUnit cu = fCompilationUnit; - - if (fCompilationUnit == null) { - return; - } - - if (cu != null) { - try { - synchronized (cu) { - cu.makeConsistent(getProgressMonitor()); - cu.reconcile(ICompilationUnit.NO_AST, true, getWorkingCopyOwner(), getProgressMonitor()); - } - } catch (JavaModelException e) { - Logger.logException(e); - } - } - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#release() - */ - public void release() { - - synchronized (fLock) { - if (fCompilationUnit != null) { - try { - if (JSPTranslation.DEBUG) { - System.out.println("------------------------------------------------------------------"); //$NON-NLS-1$ - System.out.println("(-) JSPTranslation [" + this + "] discarding CompilationUnit: " + fCompilationUnit); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println("------------------------------------------------------------------"); //$NON-NLS-1$ - } - fCompilationUnit.discardWorkingCopy(); - } catch (JavaModelException e) { - // we're done w/ it anyway - } - } - } - } - - /** - * Set contents of the compilation unit to the translated jsp text. - * - * @param the - * ICompilationUnit on which to set the buffer contents - */ - private void setContents(ICompilationUnit cu) { - if (cu == null) { - return; - } - - synchronized (cu) { - IBuffer buffer; - try { - - buffer = cu.getBuffer(); - } catch (JavaModelException e) { - e.printStackTrace(); - buffer = null; - } - - if (buffer != null) { - buffer.setContents(getJavaText()); - } - } - } - - private void setJspName(String jspName) { - fJspName = jspName; - } - - private void setMangledName(String mangledName) { - fMangledName = mangledName; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation_Interface#setProblemCollectingActive(boolean) - */ - public void setProblemCollectingActive(boolean collect) { - ICompilationUnit cu = getCompilationUnit(); - if (cu != null) { - getProblemRequestor().setIsActive(collect); - } - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationAdapter.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationAdapter.java deleted file mode 100644 index 7b81af065a..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationAdapter.java +++ /dev/null @@ -1,348 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java; - -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.DocumentEvent; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentListener; -import org.eclipse.wst.jsdt.core.IJavaProject; -import org.eclipse.wst.jsdt.core.JavaCore; -import org.eclipse.wst.jsdt.web.core.internal.Logger; -import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter; -import org.eclipse.wst.sse.core.internal.provisional.INodeNotifier; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode; - -/** - * An adapter for getting a JSPTranslation of the document. - * - * @author pavery - */ -public class JSPTranslationAdapter implements INodeAdapter, IDocumentListener { - - // for debugging - private static final boolean DEBUG = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jsptranslation")); //$NON-NLS-1$ //$NON-NLS-2$ - - private IFolder binOutput; - private boolean fDocumentIsDirty = true; - private IDocument fJavaDocument = null; - private IDocument fJspDocument = null; - private JSPTranslationExtension fJSPTranslation = null; - private NullProgressMonitor fTranslationMonitor = null; - private JSPTranslator fTranslator = null; - - private IDOMModel fXMLModel; - private IFolder srcOutput; - - public JSPTranslationAdapter(IDOMModel xmlModel) { - setXMLModel(xmlModel); - initializeJavaPlugins(); - } - - /** - * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentAboutToBeChanged(DocumentEvent event) { - // do nothing - } - - /** - * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) - */ - public void documentChanged(DocumentEvent event) { - // mark translation for rebuilding - fDocumentIsDirty = true; - } - - public String getBaseLocation() { - return getXMLModel().getBaseLocation(); - } - - public IFolder getBinLocation() { - - return this.binOutput; - } - - public IJavaProject getJavaProject() { - - IJavaProject javaProject = null; - try { - String baseLocation = getXMLModel().getBaseLocation(); - // 20041129 (pa) the base location changed for XML model - // because of FileBuffers, so this code had to be updated - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=79686 - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IPath filePath = new Path(baseLocation); - IProject project = null; - if (filePath.segmentCount() > 0) { - project = root.getProject(filePath.segment(0)); - } - - if (project != null) { - javaProject = JavaCore.create(project); - } - - // JsWebNature jsdtNature = new JsWebNature(project); - // - // if(jsdtNature.isValidJSDTProject()){ - // return jsdtNature.getJavaProject(); - // }else{ - // jsdtNature.configure(); - // return jsdtNature.getJavaProject(); - // } - - // IFile[] files = - // ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(new - // Path(baseLocation)); - // for (int i = 0; project == null && i < files.length; i++) { - // if (files[i].getType() != IResource.PROJECT) { - // project = files[i].getProject(); - // break; - // } - // } - - /* Ensure this project has the JS nature */ - // if (project != null) { - // // JavaCore.create(filePath.segment(0)); - // // System.out.println("Filepath for javaproject:"+filePath); - // javaProject = org.eclipse.jsdt.core.JavaCore.create(project); - // - // java.util.Hashtable options = org.eclipse.jsdt.core.JavaCore - // .getOptions(); - // - // Enumeration e = options.keys(); - // - // while (e.hasMoreElements()) { - // Object ne = e.nextElement(); - // ((JavaProject) javaProject).setOption((String) ne, - // (String) options.get(ne)); - // - // } - // if (javaProject instanceof JavaProject) { - // ((JavaProject) javaProject).configure(); - // - // } - // if (javaProject.getOutputLocation() == null) { - // IFolder binOutput = project.getFolder("build"); - // this.binOutput = binOutput; - // - // if (!binOutput.exists()) { - // binOutput.create(true, true, new NullProgressMonitor()); - // } - // // javaProject.setRawClasspath(entries, outputLocation, - // // monitor); - // javaProject.setOutputLocation(binOutput.getFullPath(), - // new NullProgressMonitor()); - // } else { - // this.binOutput = project.getFolder(javaProject - // .getOutputLocation()); - // } - // addContainerToClassPath(javaProject,new Path(baseLocation)); - /* - * if(javaProject instanceof JavaProject){ - * ((JavaProject)javaProject).configure(); } - * - * if( javaProject.getOutputLocation() == null){ IFolder binOutput = - * project.getFolder("bin"); this.binOutput=binOutput; - * - * - * if(!binOutput.exists()) binOutput.create(true, true, new - * NullProgressMonitor()); //javaProject.setRawClasspath(entries, - * outputLocation, monitor); - * javaProject.setOutputLocation(binOutput.getFullPath(), new - * NullProgressMonitor()); }else{ - * this.binOutput=project.getFolder(javaProject.getOutputLocation()); } - * - * srcOutput = project.getFolder("src"); if(!srcOutput.exists()) - * srcOutput.create(true, true, new NullProgressMonitor()); - */ - /* Add a src and bin folder to the projects path */ - // addSourceLocationToCp(javaProject,srcOutput.getFullPath()); - // addContainerToClassPath(javaProject,binOutput.getFullPath()); - // IProjectDescription desc = project.getDescription(); - // System.out.println("Project Name:" + desc.getName()); - // - // } - // - // if (project != null - // && !project.hasNature(JsDataTypes.natureHandlerID)) { - // IProjectDescription desc = project.getDescription(); - // String oldNatures[] = desc.getNatureIds(); - // String newNatures[] = new String[oldNatures.length + 1]; - // System.arraycopy(oldNatures, 0, newNatures, 0, - // oldNatures.length); - // newNatures[oldNatures.length] = JsDataTypes.natureHandlerID; - // desc.setNatureIds(newNatures); - // project.setDescription(desc, fTranslationMonitor); - // - // } - } catch (Exception ex) { - if (getXMLModel() != null) { - Logger.logException("(JSPTranslationAdapter) problem getting java project from the XMLModel's baseLocation > " + getXMLModel().getBaseLocation(), ex); //$NON-NLS-1$ - } else { - Logger.logException("(JSPTranslationAdapter) problem getting java project", ex); //$NON-NLS-1$ - } - } - return javaProject; - } - - /** - * Returns the JSPTranslation for this adapter. - * - * @return a JSPTranslationExtension - */ - public synchronized JSPTranslationExtension getJSPTranslation() { - - if (fJSPTranslation == null || fDocumentIsDirty) { - JSPTranslator translator = null; - if (getXMLModel() != null && getXMLModel().getIndexedRegion(0) != null) { - translator = getTranslator((IDOMNode) getXMLModel().getIndexedRegion(0)); - translator.translate(); - StringBuffer javaContents = translator.getTranslation(); - fJavaDocument = new Document(javaContents.toString()); - } else { - // empty document case - translator = new JSPTranslator(); - StringBuffer emptyContents = translator.getEmptyTranslation(); - fJavaDocument = new Document(emptyContents.toString()); - } - // it's going to be rebuilt, so we release it here - if (fJSPTranslation != null) { - if (JSPTranslationAdapter.DEBUG) { - System.out.println("JSPTranslationAdapter releasing:" + fJSPTranslation); //$NON-NLS-1$ - } - fJSPTranslation.release(); - } - fJSPTranslation = new JSPTranslationExtension(getXMLModel().getStructuredDocument(), fJavaDocument, getJavaProject(), translator); - fDocumentIsDirty = false; - } - return fJSPTranslation; - } - - /** - * Gets (or creates via JavaCore) a JavaProject based on the location of - * this adapter's XMLModel. Returns null for non IFile based models. - * - * @return the java project where - */ - // - // public IPath getWorkingDirectory() { - // if (getJavaProject() instanceof IProject) { - // return ((IProject) getJavaProject()) - // .getWorkingLocation(JsDataTypes.natureHandlerID); - // } - // return null; - // } - public IFolder getSrcLocation() { - - return this.srcOutput; - } - - /** - * Returns the JSPTranslator for this adapter. If it's null, a new - * translator is created with the xmlNode. Otherwise the - * translator.reset(xmlNode) is called to reset the current local - * translator. - * - * @param xmlNode - * the first node of the JSP document to be translated - * @return the JSPTranslator for this adapter (creates if null) - */ - private JSPTranslator getTranslator(IDOMNode xmlNode) { - if (fTranslator == null) { - fTranslationMonitor = new NullProgressMonitor(); - fTranslator = new JSPTranslator(); - fTranslator.reset(xmlNode, fTranslationMonitor); - } else { - fTranslator.reset(xmlNode, fTranslationMonitor); - } - return fTranslator; - } - - /** - * @return the XMLModel for this adapter. - */ - private IDOMModel getXMLModel() { - return fXMLModel; - } - - /** - * Initialize the required Java Plugins - */ - protected void initializeJavaPlugins() { - JavaCore.getPlugin(); - getJavaProject(); - - } - - public boolean isAdapterForType(Object type) { - return type.equals(IJSPTranslation.class); - } - - public void notifyChanged(INodeNotifier notifier, int eventType, Object changedFeature, Object oldValue, Object newValue, int pos) { - // nothing to do - } - - public void release() { - - if (fJspDocument != null) { - fJspDocument.removeDocumentListener(this); - } - - if (fTranslationMonitor != null) { - fTranslationMonitor.setCanceled(true); - } - - if (fJSPTranslation != null) { - - if (JSPTranslationAdapter.DEBUG) { - System.out.println("JSPTranslationAdapter releasing:" + fJSPTranslation); //$NON-NLS-1$ - } - - fJSPTranslation.release(); - } - } - - /** - * Automatically set through the setXMLModel(XMLModel) - * - * @param doc - */ - private void setDocument(IDocument doc) { - if (fJspDocument != null) { - fJspDocument.removeDocumentListener(this); - } - if (doc != null) { - doc.addDocumentListener(this); - fJspDocument = doc; - - } - } - - /** - * set the XMLModel for this adapter. Must be called. - * - * @param xmlModel - */ - public void setXMLModel(IDOMModel xmlModel) { - fXMLModel = xmlModel; - setDocument(fXMLModel.getStructuredDocument()); - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationAdapterFactory.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationAdapterFactory.java deleted file mode 100644 index 20605bac02..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationAdapterFactory.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.wst.sse.core.internal.provisional.AbstractAdapterFactory; -import org.eclipse.wst.sse.core.internal.provisional.INodeAdapter; -import org.eclipse.wst.sse.core.internal.provisional.INodeAdapterFactory; -import org.eclipse.wst.sse.core.internal.provisional.INodeNotifier; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode; - -/** - * Factory for JSPTranslationAdapters. - * - * @author pavery - * - */ -public class JSPTranslationAdapterFactory extends AbstractAdapterFactory { - - // for debugging - private static final boolean DEBUG; - - static { - String value = Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jsptranslation"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - private JSPTranslationAdapter fAdapter = null; - - public JSPTranslationAdapterFactory() { - super(IJSPTranslation.class, true); - } - - @Override - public INodeAdapterFactory copy() { - return new JSPTranslationAdapterFactory(); - } - - @Override - protected INodeAdapter createAdapter(INodeNotifier target) { - if (target instanceof IDOMNode && fAdapter == null) { - fAdapter = new JSPTranslationAdapter(((IDOMNode) target).getModel()); - if (JSPTranslationAdapterFactory.DEBUG) { - System.out.println("(+) JSPTranslationAdapterFactory [" + this + "] created adapter: " + fAdapter); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - return fAdapter; - } - - @Override - public void release() { - if (fAdapter != null) { - if (JSPTranslationAdapterFactory.DEBUG) { - System.out.println("(-) JSPTranslationAdapterFactory [" + this + "] releasing adapter: " + fAdapter); //$NON-NLS-1$ //$NON-NLS-2$ - } - fAdapter.release(); - } - super.release(); - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationExtension.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationExtension.java deleted file mode 100644 index 4594289f55..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationExtension.java +++ /dev/null @@ -1,397 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Position; -import org.eclipse.text.edits.DeleteEdit; -import org.eclipse.text.edits.InsertEdit; -import org.eclipse.text.edits.MalformedTreeException; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.text.edits.UndoEdit; -import org.eclipse.wst.jsdt.core.IJavaProject; -import org.eclipse.wst.jsdt.web.core.internal.Logger; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; - -/** - * Adds the notion of IDocuments (jsp Document and java Document) Used for - * TextEdit translation - * - * @author pavery - */ -public class JSPTranslationExtension extends JSPTranslation { - - // just a convenience data structure - // to keep track of java position deltas - private class PositionDelta { - - public boolean isDeleted = false; - public int postLength = 0; - public int postOffset = 0; - public int preLength = 0; - public int preOffset = 0; - - public PositionDelta(int preOffset, int preLength) { - this.preOffset = preOffset; - this.preLength = preLength; - } - - public void setPostEditData(int postOffset, int postLength, boolean isDeleted) { - this.postOffset = postOffset; - this.postLength = postLength; - this.isDeleted = isDeleted; - } - } - - // for debugging - private static final boolean DEBUG; - - static { - String value = Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jsptranslation"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - private IDocument fJavaDocument = null; - private IDocument fJspDocument = null; - - public JSPTranslationExtension(IDocument jspDocument, IDocument javaDocument, IJavaProject javaProj, JSPTranslator translator) { - super(javaProj, translator); - fJspDocument = jspDocument; - fJavaDocument = javaDocument; - - // make sure positions are added to Java and JSP documents - // this is necessary for text edits - addPositionsToDocuments(); - } - - /** - * @param translation - */ - private void addPositionsToDocuments() { - - // can be null if it's a NullJSPTranslation - if (getJavaDocument() != null && getJspDocument() != null) { - - HashMap java2jsp = getJava2JspMap(); - Iterator it = java2jsp.keySet().iterator(); - Position javaPos = null; - while (it.hasNext()) { - javaPos = (Position) it.next(); - try { - - fJavaDocument.addPosition(javaPos); - - } catch (BadLocationException e) { - if (JSPTranslationExtension.DEBUG) { - System.out.println("tyring to add Java Position:[" + javaPos.offset + ":" + javaPos.length + "] to " + getJavaPath()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - // System.out.println("substring :[" + - // fJavaDocument.get().substring(javaPos.offset) + - // "]"); //$NON-NLS-1$ //$NON-NLS-2$ - Logger.logException(e); - } - } - - try { - - fJspDocument.addPosition((Position) java2jsp.get(javaPos)); - - } catch (BadLocationException e) { - if (JSPTranslationExtension.DEBUG) { - System.out.println("tyring to add JSP Position:[" + ((Position) java2jsp.get(javaPos)).offset + ":" + ((Position) java2jsp.get(javaPos)).length + "] to " + getJavaPath()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - Logger.logException(e); - } - } - } - } - } - - private void addToMultiEdit(TextEdit edit, MultiTextEdit multiEdit) { - - // check for overlap here - // discard overlapping edits.. - // possible exponential performance hit... need a better way... - TextEdit[] children = multiEdit.getChildren(); - for (int i = 0; i < children.length; i++) { - if (children[i].covers(edit)) { - // don't add - return; - } - } - multiEdit.addChild(edit); - } - - /** - * Combines an array of edits into one MultiTextEdit (with the appropriate - * coverage region) - * - * @param edits - * @return - */ - private TextEdit createMultiTextEdit(TextEdit[] edits) { - - if (edits.length == 0) { - return new MultiTextEdit(); - } - - IRegion region = TextEdit.getCoverage(edits); - MultiTextEdit multiEdit = new MultiTextEdit(region.getOffset(), region.getLength()); - for (int i = 0; i < edits.length; i++) { - addToMultiEdit(edits[i], multiEdit); - } - return multiEdit; - } - - /** - * @param deltas - * @param jspPos - * @param replaceText - * @param jspText - * @param i - */ - private void debugReplace(PositionDelta[] deltas, Position jspPos, String replaceText, int i) { - String jspChunk; - jspChunk = getJspDocument().get().substring(jspPos.offset, jspPos.offset + jspPos.length); - if (!deltas[i].isDeleted) { - System.out.println("replacing:"); //$NON-NLS-1$ - System.out.println("jsp:[" + jspChunk + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println("w/ :[" + replaceText + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println("--------------------------------"); //$NON-NLS-1$ - } - } - - private String fixJspReplaceText(String replaceText, int jspOffset) { - - // result is the text inbetween the delimiters - // eg. - // - // <% result - // %> - String result = replaceText.trim(); - IDocument jspDoc = getJspDocument(); - if (jspDoc instanceof IStructuredDocument) { - IStructuredDocument sDoc = (IStructuredDocument) jspDoc; - IStructuredDocumentRegion[] regions = sDoc.getStructuredDocumentRegions(0, jspOffset); - - // only specifically modify scriptlets - // if (lastRegion != null - // && lastRegion.getType() == - // DOMJSPRegionContexts.JSP_SCRIPTLET_OPEN) { - // for (int i = regions.length - 1; i >= 0; i--) { - // IStructuredDocumentRegion region = regions[i]; - // - // // is there a better way to check whitespace? - // if (region.getType() == DOMRegionContext.XML_CONTENT - // && region.getFullText().trim().equals("")) { //$NON-NLS-1$ - // - // preDelimiterWhitespace = region.getFullText(); - // preDelimiterWhitespace = preDelimiterWhitespace - // .replaceAll("\r", ""); //$NON-NLS-1$ //$NON-NLS-2$ - // preDelimiterWhitespace = preDelimiterWhitespace - // .replaceAll("\n", ""); //$NON-NLS-1$ //$NON-NLS-2$ - // - // // need to determine indent for that first line... - // String initialIndent = getInitialIndent(result); - // - // // fix the first line of java code - // result = TextUtilities.getDefaultLineDelimiter(sDoc) - // + initialIndent + result; - // - // result = adjustIndent(result, preDelimiterWhitespace, - // TextUtilities.getDefaultLineDelimiter(sDoc)); - // - // // add whitespace before last delimiter to match - // // it w/ the opening delimiter - // result = result - // + TextUtilities.getDefaultLineDelimiter(sDoc) - // + preDelimiterWhitespace; - // break; - // } - // } - // } - } - return result; - } - - /** - * Recursively gets all child edits - * - * @param javaEdit - * @return all child edits - */ - private TextEdit[] getAllEdits(TextEdit javaEdit) { - - List result = new ArrayList(); - if (javaEdit instanceof MultiTextEdit) { - TextEdit[] children = javaEdit.getChildren(); - for (int i = 0; i < children.length; i++) { - result.addAll(Arrays.asList(getAllEdits(children[i]))); - } - } else { - result.add(javaEdit); - } - return (TextEdit[]) result.toArray(new TextEdit[result.size()]); - } - - public IDocument getJavaDocument() { - return fJavaDocument; - } - - @Override - public String getJavaText() { - String jsdoctext = getJavaDocument().get(); - System.out.println(jsdoctext); - return getJavaDocument() != null ? getJavaDocument().get() : ""; //$NON-NLS-1$ - } - - public IDocument getJspDocument() { - return fJspDocument; - } - - /** - * Returns a corresponding TextEdit for the JSP file given a TextEdit for a - * Java file. - * - * @param javaEdit - * @return the corresponding JSP edits (not applied to the document yet) - */ - public TextEdit getJspEdit(TextEdit javaEdit) { - - if (javaEdit == null) { - return null; - } - - List jspEdits = new ArrayList(); - - int offset = javaEdit.getOffset(); - int length = javaEdit.getLength(); - - if (javaEdit instanceof MultiTextEdit && javaEdit.getChildren().length > 0) { - - IRegion r = TextEdit.getCoverage(getAllEdits(javaEdit)); - offset = r.getOffset(); - length = r.getLength(); - } - - // get java ranges that will be affected by the edit - Position[] javaPositions = getJavaRanges(offset, length); - - // record position data before the change - Position[] jspPositions = new Position[javaPositions.length]; - PositionDelta[] deltas = new PositionDelta[javaPositions.length]; - for (int i = 0; i < javaPositions.length; i++) { - deltas[i] = new PositionDelta(javaPositions[i].offset, javaPositions[i].length); - // isIndirect means the position doesn't actually exist as exact - // text - // mapping from java <-> jsp (eg. an import statement) - if (!isIndirect(javaPositions[i].offset)) { - jspPositions[i] = (Position) getJava2JspMap().get(javaPositions[i]); - } - } - - if (JSPTranslationExtension.DEBUG) { - System.out.println("================================================"); //$NON-NLS-1$ - System.out.println("deltas:"); //$NON-NLS-1$ - String javaText = getJavaText(); - for (int i = 0; i < deltas.length; i++) { - System.out.println("pos[" + deltas[i].preOffset + ":" + deltas[i].preLength + "]" + javaText.substring(deltas[i].preOffset, deltas[i].preOffset + deltas[i].preLength)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - System.out.println("==============================================="); //$NON-NLS-1$ - } - UndoEdit undo = null; - // apply the edit to the java document - try { - undo = javaEdit.apply(getJavaDocument()); - } catch (MalformedTreeException e) { - Logger.logException(e); - } catch (BadLocationException e) { - Logger.logException(e); - } - // now at this point Java positions are unreliable since they were - // updated after applying java edit. - - String newJavaText = getJavaDocument().get(); - if (JSPTranslationExtension.DEBUG) { - System.out.println("java post format text:\n" + newJavaText); //$NON-NLS-1$ - } - - // record post edit data - for (int i = 0; i < javaPositions.length; i++) { - deltas[i].setPostEditData(javaPositions[i].offset, javaPositions[i].length, javaPositions[i].isDeleted); - } - - // create appropriate text edits for deltas - Position jspPos = null; - String replaceText = ""; //$NON-NLS-1$ - for (int i = 0; i < deltas.length; i++) { - jspPos = jspPositions[i]; - // can be null if it's an indirect mapping position - // or if something was added into java that was not originally in - // JSP (like a new import...) - - if (jspPos != null) { - if (deltas[i].isDeleted) { - jspEdits.add(new DeleteEdit(jspPos.offset, jspPos.length)); - } else { - replaceText = newJavaText.substring(deltas[i].postOffset, deltas[i].postOffset + deltas[i].postLength); - - // get rid of pre and post white space or fine tuned - // adjustment later. - // fix text here... - replaceText = fixJspReplaceText(replaceText, jspPos.offset); - - jspEdits.add(new ReplaceEdit(jspPos.offset, jspPos.length, replaceText)); - } - if (JSPTranslationExtension.DEBUG) { - debugReplace(deltas, jspPos, replaceText, i); - } - } else { - // the new Java text has no corresponding JSP position - // possible new import? - if (isImport(javaPositions[i].getOffset()) && replaceText.lastIndexOf("import ") != -1) { //$NON-NLS-1$ - replaceText = newJavaText.substring(deltas[i].postOffset, deltas[i].postOffset + deltas[i].postLength); - String importText = replaceText.substring(replaceText.lastIndexOf("import "), replaceText.indexOf(";")); //$NON-NLS-1$ //$NON-NLS-2$ - // evenutally need to check if it's XML-JSP - importText = "<%@page import=\"" + importText + "\" %>\n"; //$NON-NLS-1$ //$NON-NLS-2$ - jspEdits.add(new InsertEdit(0, importText)); - } - } - } - TextEdit allJspEdits = createMultiTextEdit((TextEdit[]) jspEdits.toArray(new TextEdit[jspEdits.size()])); - - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=105632 - // undo the java edit - // (so the underlying Java document still represents what's in the - // editor) - if (undo != null) { - try { - undo.apply(getJavaDocument()); - } catch (MalformedTreeException e) { - Logger.logException(e); - } catch (BadLocationException e) { - Logger.logException(e); - } - } - - return allJspEdits; - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationUtil.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationUtil.java deleted file mode 100644 index 3d7cf4b0cc..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslationUtil.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java; - -import org.eclipse.jface.text.IDocument; -import org.eclipse.text.edits.CopySourceEdit; -import org.eclipse.text.edits.CopyTargetEdit; -import org.eclipse.text.edits.DeleteEdit; -import org.eclipse.text.edits.InsertEdit; -import org.eclipse.text.edits.MoveSourceEdit; -import org.eclipse.text.edits.MoveTargetEdit; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.wst.jsdt.core.ICompilationUnit; -import org.eclipse.wst.jsdt.core.IJavaProject; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IModelManager; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel; - -public class JSPTranslationUtil { - protected IDocument fDocument = null; - protected JSPTranslationExtension fTranslation = null; - - public JSPTranslationUtil(IDocument document) { - fDocument = document; - } - - public ICompilationUnit getCompilationUnit() { - return getTranslation().getCompilationUnit(); - } - - public IJavaProject getJavaProject() { - return getTranslation().getJavaProject(); - } - - protected IModelManager getModelManager() { - return StructuredModelManager.getModelManager(); - } - - public JSPTranslationExtension getTranslation() { - if (fTranslation == null) { - IDOMModel xmlModel = (IDOMModel) getModelManager().getExistingModelForRead(fDocument); - try { - IDOMDocument xmlDoc = xmlModel.getDocument(); - - JSPTranslationAdapter translationAdapter = (JSPTranslationAdapter) xmlDoc.getAdapterFor(IJSPTranslation.class); - if (translationAdapter != null) { - fTranslation = translationAdapter.getJSPTranslation(); - } - } finally { - if (xmlModel != null) { - xmlModel.releaseFromRead(); - } - } - } - - return fTranslation; - } - - public TextEdit translateTextEdit(TextEdit textEdit) { - TextEdit translatedTextEdit = null; - - int javaOffset = textEdit.getOffset(); - int jspOffset = getTranslation().getJspOffset(textEdit.getOffset()); - int length = textEdit.getLength(); - - if (textEdit instanceof MultiTextEdit) { - translatedTextEdit = new MultiTextEdit(); - TextEdit[] children = ((MultiTextEdit) textEdit).getChildren(); - for (int i = 0; i < children.length; i++) { - TextEdit translatedChildTextEdit = translateTextEdit(children[i]); - if (translatedChildTextEdit != null) { - ((MultiTextEdit) translatedTextEdit).addChild(translatedChildTextEdit); - } - } - } else if (textEdit instanceof ReplaceEdit) { - if (jspOffset == -1) { - return null; - } - - if (!getTranslation().javaSpansMultipleJspPartitions(javaOffset, length)) { - translatedTextEdit = new ReplaceEdit(jspOffset, length, ((ReplaceEdit) textEdit).getText()); - } - } else if (textEdit instanceof InsertEdit) { - translatedTextEdit = new InsertEdit(jspOffset, ((InsertEdit) textEdit).getText()); - } else if (textEdit instanceof DeleteEdit) { - translatedTextEdit = new DeleteEdit(jspOffset, length); - TextEdit[] children = ((DeleteEdit) textEdit).getChildren(); - for (int i = 0; i < children.length; i++) { - TextEdit translatedChildTextEdit = translateTextEdit(children[i]); - if (translatedChildTextEdit != null) { - ((DeleteEdit) translatedTextEdit).addChild(translatedChildTextEdit); - } - } - } else if (textEdit instanceof CopySourceEdit) { - translatedTextEdit = new CopySourceEdit(jspOffset, length); - ((CopySourceEdit) translatedTextEdit).setTargetEdit(((CopySourceEdit) textEdit).getTargetEdit()); - ((CopySourceEdit) translatedTextEdit).setSourceModifier(((CopySourceEdit) textEdit).getSourceModifier()); - } else if (textEdit instanceof CopyTargetEdit) { - translatedTextEdit = new CopyTargetEdit(jspOffset); - ((CopyTargetEdit) textEdit).getSourceEdit().setTargetEdit((CopyTargetEdit) translatedTextEdit); - } else if (textEdit instanceof MoveSourceEdit) { - translatedTextEdit = new MoveSourceEdit(jspOffset, length); - ((MoveSourceEdit) translatedTextEdit).setTargetEdit(((MoveSourceEdit) textEdit).getTargetEdit()); - } else if (textEdit instanceof MoveTargetEdit) { - translatedTextEdit = new MoveTargetEdit(jspOffset); - ((MoveTargetEdit) textEdit).getSourceEdit().setTargetEdit((MoveTargetEdit) translatedTextEdit); - } else { - System.out.println("Need to translate " + textEdit); //$NON-NLS-1$ - } - - return translatedTextEdit; - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslator.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslator.java deleted file mode 100644 index 63fa38faf6..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JSPTranslator.java +++ /dev/null @@ -1,806 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java; - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import org.eclipse.core.filebuffers.FileBuffers; -import org.eclipse.core.filebuffers.ITextFileBuffer; -import org.eclipse.core.filebuffers.ITextFileBufferManager; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.Position; -import org.eclipse.wst.jsdt.web.core.internal.Logger; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionCollection; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionContainer; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode; -import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext; - -/** - * Translates a JSP document into a HttpServlet. Keeps two way mapping from java - * translation to the original JSP source, which can be obtained through - * getJava2JspRanges() and getJsp2JavaRanges(). - * - * @author pavery - */ -public class JSPTranslator { - - // for debugging - private static final boolean DEBUG; - private static final boolean DEBUG_SAVE_OUTPUT = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jsptranslationstodisk")); //$NON-NLS-1$ //$NON-NLS-2$ - public static final String ENDL = "\n"; //$NON-NLS-1$ - public static final String EXPRESSION_PREFIX = "if(document) document.write(\"\"+"; //$NON-NLS-1$ - public static final String EXPRESSION_SUFFIX = ");"; //$NON-NLS-1$ - public static final String FUNCTION_PREFIX = "function "; - - public static final String FUNCTION_SUFFIX = "} "; - - static { - String value = Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jspjavamapping"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - private String fClassname = "_JSSourceFile"; //$NON-NLS-1$ - - private IStructuredDocumentRegion fCurrentNode; - - /* the big string buffers curser position */ - // private int fCursorPosition = -1; - /* Buffer where the cursor is */ - // private StringBuffer fCursorOwner = null; // the buffer where the cursor - // is - List fGeneratedFunctionNames = new Vector(); - - /* map of imports */ - private HashMap fImportRanges = new HashMap(); - /* map of ALL ranges */ - HashMap fJava2JspRanges = new HashMap(); - - /* map of JS type ranges */ - HashMap fJsContentRanges = new HashMap(); - - /** - * save JSP document text for later use may just want to read this from the - * file or strucdtured document depending what is available - */ - private StringBuffer fJspTextBuffer = new StringBuffer(); - - /** used to avoid infinite looping include files */ - // private Stack fIncludes = null; - private IProgressMonitor fProgressMonitor = null; - - /** user defined imports */ - // private StringBuffer fUserImports = new StringBuffer(); - private StringBuffer fResult; // the - // final - // traslated - // java - // document - // string buffer - - StringBuffer fScriptText = new StringBuffer(); - private IStructuredDocument fStructuredDocument = null; - private IDOMModel fStructuredModel = null; - - /* use java script by default */ - private boolean isGlobalJs = true; - - private int scriptOffset = 0; - - private void advanceNextNode() { - setCurrentNode(getCurrentNode().getNext()); - - } - - protected void append(StringBuffer buf) { - /* - * if (getCursorOwner() == buf) { fCursorPosition = fResult.length() + - * getRelativeOffset(); } - */ - // fCursorPosition = fResult.length(); - fResult.append(buf.toString()); - } - - /** - * put the final java document together - */ - private final void buildResult() { - - // to build the java document this is the order: - // - // + default imports - // + user imports - // + class header - // [+ error page] - // + user declarations - // + service method header - // + try/catch start - // + user code - // + try/catch end - // + service method footer - - // fResult = new StringBuffer(fImplicitImports.length() + - // fUserImports.length() + fClassHeader.length() + - // fUserDeclarations.length() + fServiceHeader.length() + - // fTryCatchStart.length() // try/catch - // // start - // + fUserCode.length() + fTryCatchEnd.length() // try/catch - // // end - // + fFooter.length()); - - fResult = new StringBuffer(fScriptText.length()); - int javaOffset = 0; - append(fScriptText); - javaOffset += fScriptText.length(); - - // user imports - updateRanges(fImportRanges, javaOffset); - // append(fUserImports); - // javaOffset += fUserImports.length(); - - fJava2JspRanges.putAll(fJsContentRanges); - // fJava2JspRanges.putAll(fImportRanges); - - } - - /** - * configure using an XMLNode - * - * @param node - * @param monitor - */ - private void configure(IDOMNode node, IProgressMonitor monitor) { - - fProgressMonitor = monitor; - fStructuredModel = node.getModel(); - String baseLocation = fStructuredModel.getBaseLocation(); - - fStructuredDocument = fStructuredModel.getStructuredDocument(); - - String className = createClassname(node); - if (className.length() > 0) { - setClassname(className); - } - } - - /** - * memory saving configure (no StructuredDocument in memory) currently - * doesn't handle included files - * - * @param jspFile - * @param monitor - */ - private void configure(IFile jspFile, IProgressMonitor monitor) { - // when configured on a file - // fStructuredModel, fPositionNode, fModelQuery, fStructuredDocument - // are all null - fProgressMonitor = monitor; - - String className = createClassname(jspFile); - if (className.length() > 0) { - setClassname(className); - } - } - - /** - * @param node - * @return - */ - private String createClassname(IDOMNode node) { - - String classname = ""; //$NON-NLS-1$ - if (node != null) { - String base = node.getModel().getBaseLocation(); - classname = JSP2ServletNameUtil.mangle(base); - } - return classname; - } - - /** - * @param jspFile - * @return - */ - private String createClassname(IFile jspFile) { - - String classname = ""; //$NON-NLS-1$ - if (jspFile != null) { - classname = JSP2ServletNameUtil.mangle(jspFile.getFullPath().toString()); - } - return classname; - } - - public String getClassname() { - return this.fClassname != null ? this.fClassname : "GenericJSSourceFile"; //$NON-NLS-1$ - } - - final public IStructuredDocumentRegion getCurrentNode() { - return fCurrentNode; - } - - /** - * @return just the "shell" of a servlet, nothing contributed from the JSP - * doc - */ - public final StringBuffer getEmptyTranslation() { - reset(); - buildResult(); - return getTranslation(); - } - - public List getFakeFunctionNames() { - return fGeneratedFunctionNames; - } - - private IFile getFile() { - IFile f = null; - IStructuredModel sModel = StructuredModelManager.getModelManager().getExistingModelForRead(getStructuredDocument()); - try { - if (sModel != null) { - f = FileBuffers.getWorkspaceFileAtLocation(new Path(sModel.getBaseLocation())); - } - } finally { - if (sModel != null) { - sModel.releaseFromRead(); - } - } - return f; - } - - // final public StringBuffer getCursorOwner() { - // return fCursorOwner; - // } - - public HashMap getJava2JspImportRanges() { - return fImportRanges; - } - - public HashMap getJava2JspIndirectRanges() { - // Return nothing for now - return new HashMap(); - } - - /** - * map of ranges (positions) in java document to ranges in jsp document - * - * @return a map of java positions to jsp positions. - */ - public HashMap getJava2JspRanges() { - return fJava2JspRanges; - } - - public HashMap getJava2JspUseBeanRanges() { - // Return nothing for now - return new HashMap(); - } - - /** - * map of ranges in jsp document to ranges in java document. - * - * @return a map of jsp positions to java positions, or null if no - * translation has occured yet (the map hasn't been built). - */ - public HashMap getJsp2JavaRanges() { - if (fJava2JspRanges == null) { - return null; - } - HashMap flipFlopped = new HashMap(); - Iterator keys = fJava2JspRanges.keySet().iterator(); - - Object range = null; - while (keys.hasNext()) { - range = keys.next(); - // System.out.println("Offset:"+ p.offset + " length:" + p.length); - flipFlopped.put(fJava2JspRanges.get(range), range); - } - return flipFlopped; - } - - /** - * Only valid after a configure(...), translate(...) or - * translateFromFile(...) call - * - * @return the text in the JSP file - */ - public final String getJspText() { - return fJspTextBuffer.toString(); - } - - public IStructuredDocument getStructuredDocument() { - return fStructuredDocument; - } - - /** - * Only valid after a configure(...), translate(...) or - * translateFromFile(...) call - * - * @return the current result (java translation) buffer - */ - public final StringBuffer getTranslation() { - - if (JSPTranslator.DEBUG) { - StringBuffer debugString = new StringBuffer(); - try { - Iterator it = fJava2JspRanges.keySet().iterator(); - while (it.hasNext()) { - debugString.append("--------------------------------------------------------------\n"); //$NON-NLS-1$ - Position java = (Position) it.next(); - debugString.append("Java range:[" + java.offset + ":" + java.length + "]\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - debugString.append("[" + fResult.toString().substring(java.offset, java.offset + java.length) + "]\n"); //$NON-NLS-1$ //$NON-NLS-2$ - debugString.append("--------------------------------------------------------------\n"); //$NON-NLS-1$ - debugString.append("|maps to...|\n"); //$NON-NLS-1$ - debugString.append("==============================================================\n"); //$NON-NLS-1$ - Position jsp = (Position) fJava2JspRanges.get(java); - debugString.append("JSP range:[" + jsp.offset + ":" + jsp.length + "]\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - debugString.append("[" + fJspTextBuffer.toString().substring(jsp.offset, jsp.offset + jsp.length) + "]\n"); //$NON-NLS-1$ //$NON-NLS-2$ - debugString.append("==============================================================\n"); //$NON-NLS-1$ - debugString.append("\n"); //$NON-NLS-1$ - debugString.append("\n"); //$NON-NLS-1$ - } - } catch (Exception e) { - Logger.logException("JSPTranslation error", e); //$NON-NLS-1$ - } - Logger.log(Logger.INFO_DEBUG, debugString.toString()); - } - - if (JSPTranslator.DEBUG) { - IProject project = getFile().getProject(); - String shortenedClassname = StringUtils.replace(getFile().getName(), ".", "_"); - String filename = shortenedClassname + ".js"; - IPath path = project.getFullPath().append("src/" + filename); - try { - IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); - if (!file.exists()) { - file.create(new ByteArrayInputStream(new byte[0]), true, new NullProgressMonitor()); - } - ITextFileBufferManager textFileBufferManager = FileBuffers.getTextFileBufferManager(); - textFileBufferManager.connect(path, new NullProgressMonitor()); - ITextFileBuffer javaOutputBuffer = textFileBufferManager.getTextFileBuffer(path); - javaOutputBuffer.getDocument().set(StringUtils.replace(fResult.toString(), getClassname(), shortenedClassname)); - javaOutputBuffer.commit(new NullProgressMonitor(), true); - textFileBufferManager.disconnect(path, new NullProgressMonitor()); - } catch (Exception e) { - // this is just for debugging, ignore - } - System.out.println("Updated translation: " + path); - } - - return fResult; - } - - /** - * - * @return the status of the translator's progrss monitor, false if the - * monitor is null - */ - private boolean isCanceled() { - return (fProgressMonitor == null) ? false : fProgressMonitor.isCanceled(); - } - - /** - * Reinitialize some fields - */ - private void reset() { - - scriptOffset = 0; - // reset progress monitor - if (fProgressMonitor != null) { - fProgressMonitor.setCanceled(false); - } - - // reinit fields - - // fCursorPosition = -1; - - // fUserImports = new StringBuffer(); - fScriptText = new StringBuffer(); - - fResult = null; - - fCurrentNode = null; - - fJava2JspRanges.clear(); - fImportRanges.clear(); - fJsContentRanges.clear(); - - fJspTextBuffer = new StringBuffer(); - fGeneratedFunctionNames.clear(); - - } - - /** - * So that the JSPTranslator can be reused. - */ - public void reset(IDOMNode node, IProgressMonitor progress) { - - // initialize some things on node - configure(node, progress); - reset(); - // set the jsp text buffer - fJspTextBuffer.append(fStructuredDocument.get()); - } - - /** - * conservative version (no StructuredDocument/Model) - * - * @param jspFile - * @param progress - */ - public void reset(IFile jspFile, IProgressMonitor progress) { - - // initialize some things on node - configure(jspFile, progress); - reset(); - // set the jsp text buffer - setJspText(jspFile); - } - - public void setClassname(String classname) { - this.fClassname = classname; - } - - private IStructuredDocumentRegion setCurrentNode(IStructuredDocumentRegion currentNode) { - return this.fCurrentNode = currentNode; - } - - protected void setDocumentContent(IDocument document, InputStream contentStream, String charset) { - Reader in = null; - try { - in = new BufferedReader(new InputStreamReader(contentStream, charset), 2048); - StringBuffer buffer = new StringBuffer(2048); - char[] readBuffer = new char[2048]; - int n = in.read(readBuffer); - while (n > 0) { - buffer.append(readBuffer, 0, n); - n = in.read(readBuffer); - } - document.set(buffer.toString()); - } catch (IOException x) { - // ignore - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException x) { - // ignore - } - } - } - } - - /** - * Set the jsp text from an IFile - * - * @param jspFile - */ - private void setJspText(IFile jspFile) { - try { - BufferedInputStream in = new BufferedInputStream(jspFile.getContents()); - BufferedReader reader = new BufferedReader(new InputStreamReader(in)); - String line = null; - while ((line = reader.readLine()) != null) { - fJspTextBuffer.append(line); - fJspTextBuffer.append(JSPTranslator.ENDL); - } - reader.close(); - } catch (CoreException e) { - Logger.logException(e); - } catch (IOException e) { - Logger.logException(e); - } - } - - /* - * returns string minus CDATA open and close text - */ - final public String stripCDATA(String text) { - String resultText = ""; //$NON-NLS-1$ - String CDATA_OPEN = "<![CDATA["; //$NON-NLS-1$ - String CDATA_CLOSE = "]]>"; //$NON-NLS-1$ - int start = 0; - int end = text.length(); - while (start < text.length()) { - if (text.indexOf(CDATA_OPEN, start) > -1) { - end = text.indexOf(CDATA_OPEN, start); - resultText += text.substring(start, end); - start = end + CDATA_OPEN.length(); - } else if (text.indexOf(CDATA_CLOSE, start) > -1) { - end = text.indexOf(CDATA_CLOSE, start); - resultText += text.substring(start, end); - start = end + CDATA_CLOSE.length(); - } else { - end = text.length(); - resultText += text.substring(start, end); - break; - } - } - return resultText; - } - - public void translate() { - setCurrentNode(fStructuredDocument.getFirstStructuredDocumentRegion()); - while (getCurrentNode() != null && !isCanceled()) { - // System.out.println("Translator Looking at Node - // type:"+getCurrentNode().getType()+"---------------------------------:"); - // System.out.println(new NodeHelper(getCurrentNode())); - // i.println("/---------------------------------------------------"); - - if (getCurrentNode().getType() == DOMRegionContext.XML_TAG_NAME) { - - NodeHelper nh = new NodeHelper(getCurrentNode()); - - if ((!nh.isEndTag() || nh.isSelfClosingTag()) && nh.nameEquals("script")) { - /* - * Handles the following cases: <script - * type="javascriptype"> <script language="javascriptype> - * <script src='' type=javascriptype> <script src='' - * language=javascripttype <script src=''> global js type. - * <script> (global js type) - */ - if (NodeHelper.isInArray(JsDataTypes.JSVALIDDATATYPES, nh.getAttributeValue("type")) || NodeHelper.isInArray(JsDataTypes.JSVALIDDATATYPES, nh.getAttributeValue("language")) || isGlobalJs) { - if (nh.containsAttribute(new String[] { "src" })) { - // Handle import - translateScriptImportNode(getCurrentNode()); - } else { - // handle script section - if (getCurrentNode().getNext() != null && getCurrentNode().getNext().getType() == DOMRegionContext.BLOCK_TEXT) { - translateJSNode(getCurrentNode().getNext()); - } - } - } // End search for <script> sections - } else if (nh.containsAttribute(JsDataTypes.HTMLATREVENTS)) { - /* Check for embeded JS events in any tags */ - translateInlineJSNode(getCurrentNode()); - } else if (nh.nameEquals("META") && nh.attrEquals("http-equiv", "Content-Script-Type") && nh.containsAttribute(new String[] { "content" })) { - // <META http-equiv="Content-Script-Type" content="type"> - isGlobalJs = NodeHelper.isInArray(JsDataTypes.JSVALIDDATATYPES, nh.getAttributeValue("content")); - } // End big if of JS types - } - if (getCurrentNode() != null) { - advanceNextNode(); - } - } // end while loop - buildResult(); - - } - - public void translateInlineJSNode(IStructuredDocumentRegion container) { - // System.out - // .println("JSPTranslator.translateInlineJSNode Entered - // w/ScriptOffset:" - // + scriptOffset); - - NodeHelper nh = new NodeHelper(container); - // System.out.println("inline js node looking at:\n" + nh); - /* start a function header.. will amend later */ - String functionConstant = "function "; - String header = "_" + nh.getElementAsFlatString(); - String footer = "}"; - - /* Start looping through the region. May have mutlipel even attribs */ - if (container == null) { - return; - } - - ITextRegionList t = container.getRegions(); - ITextRegion r; - Iterator regionIterator = t.iterator(); - while (regionIterator.hasNext()) { - r = (ITextRegion) regionIterator.next(); - if (r.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME) { - int start = r.getStart(); - int offset = r.getTextEnd(); - - String tagAttrname = container.getText().substring(start, offset).trim(); - - /* - * Attribute values aren't case sensative, also make sure next - * region is attrib value - */ - if (NodeHelper.isInArray(JsDataTypes.HTMLATREVENTS, tagAttrname)) { - if (regionIterator.hasNext()) { - regionIterator.next(); - } - if (regionIterator.hasNext()) { - r = ((ITextRegion) regionIterator.next()); - } - - if (r.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE) { - - int valStartOffset = container.getStartOffset(r); - // int valEndOffset = r.getTextEnd(); - String rawText = container.getText().substring(r.getStart(), r.getTextEnd()); - - String newFunctionHeader = functionConstant + header + "_" + scriptOffset + tagAttrname + "(){"; - /* add functiont to invalid function name list */ - fGeneratedFunctionNames.add(new String(header + "_" + scriptOffset + tagAttrname)); - - String rawFunction = nh.stripEndQuotes(rawText); - - /* - * Determine if we should put a ; after the raw function - * text - */ - boolean needsSemiColon = !(rawFunction.length() > 0 && rawFunction.trim().charAt(rawFunction.trim().length() - 1) == ';'); - - int offsetForQutoes = (nh.isQuoted(rawText)) ? 1 : 0; - - Position inScript = new Position(scriptOffset + newFunctionHeader.length(), rawFunction.length()); - - /* Quoted text starts +1 and ends -1 char */ - Position inHtml = new Position(valStartOffset + offsetForQutoes, rawText.length() - 2 * offsetForQutoes); - - /* - * build the function. Addiotional function "baggage" - * not of concern to editor - */ - String emulatedFunction = newFunctionHeader + rawFunction + (needsSemiColon ? ";" : "") + footer; - - fJsContentRanges.put(inScript, inHtml); - fScriptText.append(emulatedFunction); - scriptOffset = fScriptText.length(); - if (JSPTranslator.DEBUG) { - System.out.println("START-----------------JS Translator Script loop---------------"); - System.out.println("Translated to:\n" + emulatedFunction + "\n"); - System.out.println("HTML Position:[" + inHtml.getOffset() + "," + inHtml.getLength() + "]"); - System.out.println("Script Position:[" + inScript.getOffset() + "," + inScript.getLength() + "]"); - System.out.println("Added (js) Text length:" + emulatedFunction.length()); - System.out.println("END-----------------JS Translator Script loop---------------"); - } - } - } - } - - } - // System.out - // .println("JSPTranslator.translateInlineJSNode Left w/ScriptOffset:" - // + scriptOffset); - - } - - public void translateJSNode(IStructuredDocumentRegion container) { - - ITextRegionCollection containerRegion = container; - Iterator regions = containerRegion.getRegions().iterator(); - ITextRegion region = null; - while (regions.hasNext()) { - region = (ITextRegion) regions.next(); - String type = region.getType(); - // content assist was not showing up in JSP inside a javascript - // region - if (type == DOMRegionContext.BLOCK_TEXT) { - int scriptStart = container.getStartOffset(); - int scriptTextEnd = container.getEndOffset() - container.getStartOffset(); - - // - // System.out.println("Container getStartOffset():" + - // container.getStartOffset()); - // System.out.println("Container getEnd():" + - // container.getEnd()); - // System.out.println("Container getEndOffset():" + - // container.getEndOffset()); - // System.out.println("Container getType():" + - // container.getType()); - // - // System.out.println("Region getStart():" + region.getStart()); - // System.out.println("Region getEnd():" + region.getStart()); - // System.out.println("Region getType():" + region.getType()); - // System.out.println("Container Text Length:" + - // container.getText().length()); - // - // System.out.println("Container Text:" + container.getText()); - - String regionText = container.getText().substring(region.getStart(), region.getEnd()); - int regionLength = regionText.length(); - Position inScript = new Position(scriptOffset, regionLength); - Position inHtml = new Position(scriptStart, scriptTextEnd); - if (JSPTranslator.DEBUG) { - System.out.println("START-----------------JS Translator Script loop---------------"); - System.out.println("Translated to:\n" + regionText + "\n"); - System.out.println("HTML Position:[" + inHtml.getOffset() + "," + inHtml.getLength() + "]"); - System.out.println("Script Position:[" + inScript.getOffset() + "," + inScript.getLength() + "]"); - System.out.println("END-----------------JS Translator Script loop---------------"); - // - } - fJsContentRanges.put(inScript, inHtml); - fScriptText.append(regionText); - - scriptOffset = fScriptText.length(); - - // System.out - // .println("JSPTranslator.translateJSNode Left w/ScriptOffset:" - // + scriptOffset); - } - } - } - - // final public int getCursorPosition() { - // return fCursorPosition; - // } - - public void translateScriptImportNode(IStructuredDocumentRegion region) { - - } - - /** - * @param r - * the region to be unescaped (XMLContent, XML ENTITY REFERENCE, - * or CDATA) - * @param sb - * the stringbuffer to append the text to - * @return the number of characters removed in unescaping this text - */ - protected int unescapeRegion(ITextRegion r, StringBuffer sb) { - String s = ""; //$NON-NLS-1$ - int lengthBefore = 0, lengthAfter = 0, cdata_tags_length = 0; - if (r != null && (r.getType() == DOMRegionContext.XML_CONTENT || r.getType() == DOMRegionContext.XML_ENTITY_REFERENCE)) { - lengthBefore = (getCurrentNode() != r) ? getCurrentNode().getFullText(r).length() : getCurrentNode().getFullText().length(); - s = EscapedTextUtil.getUnescapedText(getCurrentNode(), r); - lengthAfter = s.length(); - sb.append(s); - } else if (r != null && r.getType() == DOMRegionContext.XML_CDATA_TEXT) { - if (r instanceof ITextRegionContainer) // only interested in - // contents - { - // navigate to next region container (which should be a JSP - // region) - Iterator it = ((ITextRegionContainer) r).getRegions().iterator(); - ITextRegion temp = null; - while (it.hasNext()) { - temp = (ITextRegion) it.next(); - if (temp instanceof ITextRegionContainer || temp.getType() == DOMRegionContext.XML_CDATA_TEXT) { - sb.append(getCurrentNode().getFullText(temp)); - } else if (temp.getType() == DOMRegionContext.XML_CDATA_OPEN || temp.getType() == DOMRegionContext.XML_CDATA_CLOSE) { - cdata_tags_length += temp.getLength(); - } - } - } - } - return (lengthBefore - lengthAfter + cdata_tags_length); - } - - /** - * @param javaRanges - * @param offsetInJava - */ - private void updateRanges(HashMap rangeMap, int offsetInJava) { - // just need to update java ranges w/ the offset we now know - Iterator it = rangeMap.keySet().iterator(); - while (it.hasNext()) { - ((Position) it.next()).offset += offsetInJava; - } - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JsDataTypes.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JsDataTypes.java deleted file mode 100644 index f734b426aa..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/JsDataTypes.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.eclipse.wst.jsdt.web.core.internal.java; - -import org.eclipse.wst.html.core.internal.provisional.HTML40Namespace; -import org.eclipse.wst.html.core.text.IHTMLPartitions; - -public interface JsDataTypes extends HTML40Namespace { - /* - * remove when when we refactor (need to add this content type to many - * project types in wst) - */ - - public static final String BASE_FILE_EXTENSION = ".js"; - - public static String[] CONSTANTS = { "false", "null", "true" }; //$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$ - - public static final String[] EVENTS = { HTML40Namespace.ATTR_NAME_ONCLICK, HTML40Namespace.ATTR_NAME_ONDBLCLICK, HTML40Namespace.ATTR_NAME_ONMOUSEDOWN, HTML40Namespace.ATTR_NAME_ONMOUSEUP, HTML40Namespace.ATTR_NAME_ONMOUSEOVER, HTML40Namespace.ATTR_NAME_ONMOUSEMOVE, HTML40Namespace.ATTR_NAME_ONMOUSEOUT, HTML40Namespace.ATTR_NAME_ONKEYPRESS, HTML40Namespace.ATTR_NAME_ONKEYDOWN, HTML40Namespace.ATTR_NAME_ONKEYUP, HTML40Namespace.ATTR_NAME_ONHELP }; - - public static final String[] HTMLATREVENTS = { "onload ", "onunload", "onclick", - - "onmousedown", "onmouseup", "onmouseover", "onmousemove", "onmouseout", "onfocus", "onblur", "onkeypress", "onkeydown", "onkeyup", "onsubmit", "onreset", "onselect", "onchange", }; - - public static final String[] JSVALIDDATATYPES = { "JAVASCRIPT", "TEXT/JAVASCRIPT" }; //$NON-NLS-1$ - - public static String[] KEYWORDS = { "abstract", - - "break", - - "case", "catch", - - "class", "const", "continue", "debugger", "default", "delete", "do", - - "else", "enum", "export", "extends", - - "final", "finally", - - "for", "function", "goto", "if", "implements", "import", "in", "instanceof", - - "interface", - - "native", "new", - - "package", "private", "protected", "public", "return", - - "static", "super", "switch", "synchronized", "this", "throw", "throws", "transient", - - "try", "typeof", "volatile", "while", "with" }; //$NON-NLS-1$ - // public static final String - // NEW_PARTITION_TYPE="org.eclipse.wst.jsdt.StructuredJs"; - // public static final String NEW_PARTITION_TYPE=IHTMLPartitions.SCRIPT; - public static final String NEW_PARTITION_TYPE = IHTMLPartitions.SCRIPT; - public static final String[] TAKEOVER_PARTITION_TYPES = { "none" }; - public static String[] TYPES = { "boolean", "byte", "char", "double", "int", "long", "short", "float", "var", "void" }; //$NON-NLS-1$ - -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/NodeHelper.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/NodeHelper.java deleted file mode 100644 index 1f61ae2433..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/NodeHelper.java +++ /dev/null @@ -1,262 +0,0 @@ -package org.eclipse.wst.jsdt.web.core.internal.java; - -import java.util.Iterator; - -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; -import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext; - -public class NodeHelper { - - protected static final char DOUBLE_QUOTE_CHAR = '\"'; - protected static final String DOUBLE_QUOTE_ENTITY = """; //$NON-NLS-1$ - protected static final char SINGLE_QUOTE_CHAR = '\''; - protected static final String SINGLE_QUOTE_ENTITY = "'"; //$NON-NLS-1$ - - public static boolean isInArray(String StringArray[], String text) { - if (StringArray == null || text == null) { - return false; - } - - for (int i = 0; i < StringArray.length; i++) { - if (StringArray[i].equalsIgnoreCase(text.trim())) { - return true; - } - } - return false; - } - - public static boolean isQuoted(String string) { - if ((string == null) || (string.length() < 2)) { - return false; - } - - int lastIndex = string.length() - 1; - char firstChar = string.charAt(0); - char lastChar = string.charAt(lastIndex); - - return (((firstChar == NodeHelper.SINGLE_QUOTE_CHAR) && (lastChar == NodeHelper.SINGLE_QUOTE_CHAR)) || ((firstChar == NodeHelper.DOUBLE_QUOTE_CHAR) && (lastChar == NodeHelper.DOUBLE_QUOTE_CHAR))); - } - - protected final IStructuredDocumentRegion region; - - public NodeHelper(IStructuredDocumentRegion region) { - this.region = region; - } - - public boolean attrEquals(String attribute, String value) { - return (new String(getAttributeValue(attribute))).equalsIgnoreCase(value); - } - - public String AttrToString() { - if (region == null) { - return null; - } - // For debuging - ITextRegionList t = region.getRegions(); - ITextRegion r; - Iterator regionIterator = t.iterator(); - String StructuredValue = "Tag name:" + getTagName() + "\tAttribute\tValue\n"; - while (regionIterator.hasNext()) { - r = (ITextRegion) regionIterator.next(); - if (r.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME) { - int start = r.getStart(); - int offset = r.getTextEnd(); - StructuredValue += "\t\t" + region.getText().substring(start, offset); - /* - * Theres a XML_TAG_ATTRIBUTE_EQUALS after the - * XML_TAG_ATTRIBUTE_NAME we have to get rid of - */ - if (regionIterator.hasNext()) { - regionIterator.next(); - } - if (regionIterator.hasNext()) { - r = ((ITextRegion) regionIterator.next()); - } - System.out.println("attrib type"); - if (r.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE) { - int valStart = r.getStart(); - int valOffset = r.getTextEnd(); - StructuredValue += "\t\t" + stripEndQuotes(region.getText().substring(valStart, valOffset)) + "\n"; - } - - } - - } - return StructuredValue; - - } - - public boolean containsAttribute(String name[]) { - if (name == null) { - return false; - } - if (region == null) { - return false; - } - ITextRegionList t = region.getRegions(); - ITextRegion r; - Iterator regionIterator = t.iterator(); - while (regionIterator.hasNext()) { - r = (ITextRegion) regionIterator.next(); - if (r.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME) { - int start = r.getStart(); - int offset = r.getTextEnd(); - String tagname = region.getText().substring(start, offset).trim(); - /* Attribute values aren't case sensative */ - if (NodeHelper.isInArray(name, tagname)) { - return true; - } - } - } - return false; - } - - public String getAttributeValue(String name) { - if (region == null) { - return null; - } - if (name == null) { - return null; - } - ITextRegionList t = region.getRegions(); - ITextRegion r; - Iterator regionIterator = t.iterator(); - while (regionIterator.hasNext()) { - r = (ITextRegion) regionIterator.next(); - if (r.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME) { - int start = r.getStart(); - int offset = r.getTextEnd(); - - String tagname = region.getText().substring(start, offset).trim(); - /* - * Attribute values aren't case sensative, also make sure next - * region is attrib value - */ - if (tagname.equalsIgnoreCase(name)) { - if (regionIterator.hasNext()) { - regionIterator.next(); - } - if (regionIterator.hasNext()) { - r = ((ITextRegion) regionIterator.next()); - } - - if (r.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE) { - int valStart = r.getStart(); - int valOffset = r.getTextEnd(); - return stripEndQuotes(region.getText().substring(valStart, valOffset)); - } - } - } - - } - return null; - } - - public String getElementAsFlatString() { - /* - * Returns a full string of this element minus and 'illegal' characters - * (usefull for identifying the HTML element in a generic JS function) - */ - if (region == null) { - return null; - } - - String fullRegionText = region.getFullText(); - - if (fullRegionText == null) { - return null; - } - - return fullRegionText.replaceAll("[^a-zA-Z0-9]", ""); - } - - public String getTagName() { - if (region == null) { - return null; - } - ITextRegionList t = region.getRegions(); - ITextRegion r; - Iterator regionIterator = t.iterator(); - while (regionIterator.hasNext()) { - r = (ITextRegion) regionIterator.next(); - - if (r.getType() == DOMRegionContext.XML_TAG_NAME) { - int start = r.getStart(); - int offset = r.getTextEnd(); - return region.getText().substring(start, offset); - } - - } - - return null; - } - - public boolean isEndTag() { - - if (region == null) { - return false; - } - ITextRegionList t = region.getRegions(); - ITextRegion r; - Iterator regionIterator = t.iterator(); - while (regionIterator.hasNext()) { - r = (ITextRegion) regionIterator.next(); - if (r.getType() == DOMRegionContext.XML_END_TAG_OPEN) { - return true; - } - } - return false; - } - - public boolean isSelfClosingTag() { - if (region == null) { - return false; - } - - if (region == null) { - return false; - } - - ITextRegionList regions = region.getRegions(); - ITextRegion r = regions.get(regions.size() - 1); - return r.getType() == DOMRegionContext.XML_EMPTY_TAG_CLOSE; - } - - public boolean nameEquals(String name) { - if (region == null) { - return false; - } - return (getTagName().equalsIgnoreCase(name)); - } - - public String stripEndQuotes(String text) { - if (text == null) { - return null; - } - if (NodeHelper.isQuoted(text)) { - return text.substring(1, text.length() - 1); - } - - return text; - - } - - @Override - public String toString() { - ITextRegionList t = region.getRegions(); - - Iterator regionIterator = t.iterator(); - String nodeText = new String(); - - while (regionIterator.hasNext()) { - - ITextRegion r = (ITextRegion) regionIterator.next(); - String nodeType = r.getType(); - nodeText += ("\tNode Type:" + nodeType + " \t\tValue:" + region.getText().substring(r.getStart(), r.getTextEnd()) + "\n"); - } - return nodeText; - } - -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/IndexWorkspaceJob.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/IndexWorkspaceJob.java deleted file mode 100644 index bfa499bdb5..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/IndexWorkspaceJob.java +++ /dev/null @@ -1,175 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java.search; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceProxy; -import org.eclipse.core.resources.IResourceProxyVisitor; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.wst.jsdt.web.core.internal.JSPCoreMessages; -import org.eclipse.wst.jsdt.web.core.internal.provisional.contenttype.ContentTypeIdForJSP; - -/** - * Re-indexes the entire workspace. Ensures the JSP Index is in a stable state - * before performing a search. (like after a crash or if previous indexing was - * canceled) - * - * @author pavery - */ -public class IndexWorkspaceJob extends Job { - - /** - * Visitor that retrieves jsp project paths for all jsp files in the - * workspace, and adds the files to be indexed as they are encountered - */ - private class JSPFileVisitor implements IResourceProxyVisitor { - private List files = new ArrayList(); - - // monitor from the Job - IProgressMonitor fInnerMonitor = null; - - public JSPFileVisitor(IProgressMonitor monitor) { - this.fInnerMonitor = monitor; - } - - public final IFile[] getFiles() { - return (IFile[]) this.files.toArray(new IFile[this.files.size()]); - } - - public boolean visit(IResourceProxy proxy) throws CoreException { - - // check job canceled - if (this.fInnerMonitor != null && this.fInnerMonitor.isCanceled()) { - setCanceledState(); - return false; - } - - // check search support canceled - if (JSPSearchSupport.getInstance().isCanceled()) { - setCanceledState(); - return false; - } - - if (proxy.getType() == IResource.FILE) { - - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=3553 - // check this before description - // check name before actually getting the file (less work) - if (getJspContentType().isAssociatedWith(proxy.getName())) { - IFile file = (IFile) proxy.requestResource(); - if (file.exists()) { - - if (IndexWorkspaceJob.DEBUG) { - System.out.println("(+) IndexWorkspaceJob adding file: " + file.getName()); //$NON-NLS-1$ - } - // this call will check the ContentTypeDescription, so - // don't need to do it here. - // JSPSearchSupport.getInstance().addJspFile(file); - this.files.add(file); - this.fInnerMonitor.subTask(proxy.getName()); - - // don't search deeper for files - return false; - } - } - } - return true; - } - } - - // for debugging - static final boolean DEBUG; - - static { - String value = Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jspindexmanager"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - private IContentType fContentTypeJSP = null; - - public IndexWorkspaceJob() { - // pa_TODO may want to say something like "Rebuilding JSP Index" to be - // more - // descriptive instead of "Updating JSP Index" since they are 2 - // different things - super(JSPCoreMessages.JSPIndexManager_0); - setPriority(Job.LONG); - setSystem(true); - } - - IContentType getJspContentType() { - if (this.fContentTypeJSP == null) { - this.fContentTypeJSP = Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSP); - } - return this.fContentTypeJSP; - } - - /** - * @see org - * eclipse.core.internal.jobs.InternalJob#run(org.eclipse.core.runtime.IProgressMonitor) - * for similar method - */ - @Override - protected IStatus run(IProgressMonitor monitor) { - - IStatus status = Status.OK_STATUS; - - if (monitor.isCanceled()) { - setCanceledState(); - return Status.CANCEL_STATUS; - } - - if (IndexWorkspaceJob.DEBUG) { - System.out.println(" ^ IndexWorkspaceJob started: "); //$NON-NLS-1$ - } - - long start = System.currentTimeMillis(); - - try { - JSPFileVisitor visitor = new JSPFileVisitor(monitor); - // collect all jsp files - ResourcesPlugin.getWorkspace().getRoot().accept(visitor, IResource.DEPTH_INFINITE); - // request indexing - // this is pretty much like faking an entire workspace resource - // delta - JSPIndexManager.getInstance().indexFiles(visitor.getFiles()); - } catch (CoreException e) { - if (IndexWorkspaceJob.DEBUG) { - e.printStackTrace(); - } - } finally { - if (monitor != null) { - monitor.done(); - } - } - long finish = System.currentTimeMillis(); - if (IndexWorkspaceJob.DEBUG) { - System.out.println(" ^ IndexWorkspaceJob finished\n total time running: " + (finish - start)); //$NON-NLS-1$ - } - - return status; - } - - void setCanceledState() { - JSPIndexManager.getInstance().setIndexState(JSPIndexManager.S_CANCELED); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPIndexManager.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPIndexManager.java deleted file mode 100644 index f8bc712f4f..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPIndexManager.java +++ /dev/null @@ -1,724 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java.search; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceChangeEvent; -import org.eclipse.core.resources.IResourceChangeListener; -import org.eclipse.core.resources.IResourceDelta; -import org.eclipse.core.resources.IResourceDeltaVisitor; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Plugin; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.jobs.IJobChangeEvent; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.core.runtime.jobs.JobChangeAdapter; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.jsdt.internal.core.JavaModelManager; -import org.eclipse.wst.jsdt.internal.core.index.Index; -import org.eclipse.wst.jsdt.internal.core.search.indexing.IndexManager; -import org.eclipse.wst.jsdt.web.core.internal.JSPCoreMessages; -import org.eclipse.wst.jsdt.web.core.internal.JSPCorePlugin; -import org.eclipse.wst.jsdt.web.core.internal.Logger; -import org.eclipse.wst.jsdt.web.core.internal.provisional.contenttype.ContentTypeIdForJSP; -import org.osgi.framework.Bundle; - -/** - * Responsible for keeping the JSP index up to date. - * - * @author pavery - */ -public class JSPIndexManager { - - private class IndexJobCoordinator extends JobChangeAdapter { - - @Override - public void aboutToRun(IJobChangeEvent event) { - Job jobToCoordinate = event.getJob(); - if (isJobToAvoid(jobToCoordinate)) { - // job will be rescheduled when the job we - // are avoiding (eg. build) is done - getProcessFilesJob().cancel(); - // System.out.println("cancel:" + jobToCoordinate.getName()); - } - } - - @Override - public void done(IJobChangeEvent event) { - - Job jobToCoordinate = event.getJob(); - if (isJobToAvoid(jobToCoordinate)) { - if (getProcessFilesJob().getFiles().length > 0) { - getProcessFilesJob().schedule(500); - // System.out.println("schedule:" + - // jobToCoordinate.getName()); - } - - } - } - - private boolean isJobToAvoid(Job jobToCoordinate) { - boolean result = false; - if (jobToCoordinate.belongsTo(ResourcesPlugin.FAMILY_AUTO_BUILD) || jobToCoordinate.belongsTo(ResourcesPlugin.FAMILY_MANUAL_BUILD) || jobToCoordinate.belongsTo(ResourcesPlugin.FAMILY_AUTO_REFRESH)) { - result = true; - } - return result; - - } - - } - - private class JSPResourceChangeListener implements IResourceChangeListener { - - /** - * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent) - */ - public void resourceChanged(IResourceChangeEvent event) { - - if (isInitializing()) { - return; - } - - // ignore resource changes if already rebuilding - if (getIndexState() == JSPIndexManager.S_REBUILDING) { - return; - } - // previously canceled, needs entire index rebuild - if (getIndexState() == JSPIndexManager.S_CANCELED) { - // rebuildIndex(); - // just resume indexing - getProcessFilesJob().schedule(500); - // System.out.println("schedule: resource changed, previously - // canceled"); - return; - } - - IResourceDelta delta = event.getDelta(); - if (delta != null) { - // only care about adds or changes right now... - int kind = delta.getKind(); - boolean added = (kind & IResourceDelta.ADDED) == IResourceDelta.ADDED; - boolean changed = (kind & IResourceDelta.CHANGED) == IResourceDelta.CHANGED; - if (added || changed) { - - // only analyze the full (starting at root) delta - // hierarchy - if (delta.getFullPath().toString().equals("/")) { //$NON-NLS-1$ - try { - JSPResourceVisitor v = getVisitor(); - // clear from last run - v.reset(); - // count files, possibly do this in a job too... - // don't include PHANTOM resources - delta.accept(v, false); - - // process files from this delta - IFile[] files = v.getFiles(); - if (files.length > 0) { - /* - * Job change listener should set back to stable - * when finished - */ - setUpdatingState(); - // processFiles(files); - indexFiles(files); - } - } catch (CoreException e) { - // need to set state here somehow, and reindex - // otherwise index will be unreliable - if (JSPIndexManager.DEBUG) { - Logger.logException(e); - } - } catch (Exception e) { - // need to set state here somehow, and reindex - // otherwise index will be unreliable - if (JSPIndexManager.DEBUG) { - Logger.logException(e); - } - } - } - } - - } - } - - } - - /** - * Collects JSP files from a resource delta. - */ - private class JSPResourceVisitor implements IResourceDeltaVisitor { - // using hash map ensures only one of each file - // must be reset before every use - private HashMap jspFiles = null; - - public JSPResourceVisitor() { - this.jspFiles = new HashMap(); - } - - private void deleteIndex(IFile folder) { - // cleanup index - IndexManager im = JavaModelManager.getJavaModelManager().getIndexManager(); - IPath folderPath = folder.getFullPath(); - IPath indexLocation = JSPSearchSupport.getInstance().computeIndexLocation(folderPath); - im.removeIndex(indexLocation); - // im.indexLocations.removeKey(folderPath); - // im.indexLocations.removeValue(indexLocation); - File f = indexLocation.toFile(); - f.delete(); - } - - public IFile[] getFiles() { - return (IFile[]) this.jspFiles.values().toArray(new IFile[this.jspFiles.size()]); - } - - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=93463 - private boolean isHiddenResource(IPath p) { - String[] segments = p.segments(); - for (int i = 0; i < segments.length; i++) { - if (segments[i].startsWith(".")) { - return true; - } - } - return false; - } - - public void reset() { - this.jspFiles.clear(); - } - - public boolean visit(IResourceDelta delta) throws CoreException { - - // in case JSP search was canceled (eg. when closing the editor) - if (JSPSearchSupport.getInstance().isCanceled() || frameworkIsShuttingDown()) { - setCanceledState(); - return false; - } - - try { - if (!isHiddenResource(delta.getFullPath())) { - - int kind = delta.getKind(); - boolean added = (kind & IResourceDelta.ADDED) == IResourceDelta.ADDED; - boolean isInterestingChange = false; - if ((kind & IResourceDelta.CHANGED) == IResourceDelta.CHANGED) { - int flags = delta.getFlags(); - // ignore things like marker changes - isInterestingChange = (flags & IResourceDelta.CONTENT) == IResourceDelta.CONTENT || (flags & IResourceDelta.REPLACED) == IResourceDelta.REPLACED; - } - boolean removed = (kind & IResourceDelta.REMOVED) == IResourceDelta.REMOVED; - if (added || isInterestingChange) { - - visitAdded(delta); - } else if (removed) { - visitRemoved(delta); - } - } - } catch (Exception e) { - // need to set state here somehow, and reindex - // otherwise index will be unreliable - if (JSPIndexManager.DEBUG) { - Logger.logException("Delta analysis may not be complete", e); //$NON-NLS-1$ - } - } - // if the delta has children, continue to add/remove files - return true; - } - - private void visitAdded(IResourceDelta delta) { - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=3553 - // quick check if it's even JSP related to improve - // performance - // checking name from the delta before getting - // resource because it's lighter - int numSegments = delta.getFullPath().segmentCount(); - String filename = delta.getFullPath().segment(numSegments - 1); - if (getJspContentType().isAssociatedWith(filename)) { - IResource r = delta.getResource(); - if (r != null && r.exists() && r.getType() == IResource.FILE) { - this.jspFiles.put(r.getFullPath(), r); - } - } - } - - private void visitRemoved(IResourceDelta delta) { - // handle cleanup - if (delta.getResource() != null) { - IResource r = delta.getResource(); - if (r.getType() == IResource.FOLDER && r.exists()) { - deleteIndex((IFile) r); - } - } - } - } - - /** - * schedules JSP files for indexing by Java core - */ - private class ProcessFilesJob extends Job { - List fileList = null; - // keep track of how many files we've indexed - int lastFileCursor = 0; - - ProcessFilesJob(String taskName) { - super(taskName); - fileList = new ArrayList(); - } - - synchronized void clearFiles() { - fileList.clear(); - lastFileCursor = 0; - // System.out.println("cleared files"); - } - - synchronized IFile[] getFiles() { - return (IFile[]) fileList.toArray(new IFile[fileList.size()]); - } - - private boolean isCanceled(IProgressMonitor runMonitor) { - - boolean canceled = false; - // check specific monitor passed into run method (the progress - // group in this case) - // check main search support canceled - if (runMonitor != null && runMonitor.isCanceled()) { - canceled = true; - } else if (JSPSearchSupport.getInstance().isCanceled()) { - canceled = true; - if (runMonitor != null) { - runMonitor.setCanceled(true); - } - } - return canceled; - } - - synchronized void process(IFile[] files) { - for (int i = 0; i < files.length; i++) { - fileList.add(files[i]); - } - if (JSPIndexManager.DEBUG) { - System.out.println("JSPIndexManager queuing " + files.length + " files"); //$NON-NLS-2$ //$NON-NLS-1$ - } - } - - @Override - protected IStatus run(IProgressMonitor monitor) { - // System.out.println("indexer monitor" + monitor); - if (isCanceled(monitor) || frameworkIsShuttingDown()) { - setCanceledState(); - return Status.CANCEL_STATUS; - } - - long start = System.currentTimeMillis(); - - try { - IFile[] filesToBeProcessed = getFiles(); - - if (JSPIndexManager.DEBUG) { - System.out.println("JSPIndexManager indexing " + filesToBeProcessed.length + " files"); //$NON-NLS-2$ //$NON-NLS-1$ - } - // API indicates that monitor is never null - monitor.beginTask("", filesToBeProcessed.length); //$NON-NLS-1$ - JSPSearchSupport ss = JSPSearchSupport.getInstance(); - String processingNFiles = ""; //$NON-NLS-1$ - - for (; lastFileCursor < filesToBeProcessed.length; lastFileCursor++) { - - if (isCanceled(monitor) || frameworkIsShuttingDown()) { - setCanceledState(); - return Status.CANCEL_STATUS; - } - try { - ss.addJspFile(filesToBeProcessed[lastFileCursor]); - // JSP Indexer processing n files - processingNFiles = NLS.bind(JSPCoreMessages.JSPIndexManager_2, new String[] { Integer.toString((filesToBeProcessed.length - lastFileCursor)) }); - monitor.subTask(processingNFiles + " - " + filesToBeProcessed[lastFileCursor].getName()); //$NON-NLS-1$ - monitor.worked(1); - - if (JSPIndexManager.DEBUG) { - System.out.println("JSPIndexManager Job added file: " + filesToBeProcessed[lastFileCursor].getName()); //$NON-NLS-1$ - } - } catch (Exception e) { - // RATLC00284776 - // ISSUE: we probably shouldn't be catching EVERY - // exception, but - // the framework only allows to return IStatus in - // order to communicate - // that something went wrong, which means the loop - // won't complete, and we would hit the same problem - // the next time. - // - // a possible solution is to keep track of the - // exceptions logged - // and only log a certain amt of the same one, - // otherwise skip it. - if (!frameworkIsShuttingDown()) { - String filename = filesToBeProcessed[lastFileCursor] != null ? filesToBeProcessed[lastFileCursor].getFullPath().toString() : ""; //$NON-NLS-1$ - Logger.logException("JSPIndexer problem indexing:" + filename, e); //$NON-NLS-1$ - } - } - } // end for - } finally { - // just in case something didn't follow API (monitor is null) - if (monitor != null) { - monitor.done(); - } - } - - // successfully finished, clear files list - clearFiles(); - - long finish = System.currentTimeMillis(); - long diff = finish - start; - if (JSPIndexManager.DEBUG) { - JSPIndexManager.fTotalTime += diff; - System.out.println("============================================================================"); //$NON-NLS-1$ - System.out.println("this time: " + diff + " cumulative time for resource changed: " + JSPIndexManager.fTotalTime); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println("============================================================================"); //$NON-NLS-1$ - } - return Status.OK_STATUS; - } - - } - - // TODO: consider enumeration for these int constants - // set to S_UPDATING once a resource change comes in - // set to S_STABLE if: - // - we know we aren't interested in the resource change - // - or the ProcessFilesJob completes - // set to S_CANCELED if an indexing job is canceled - // set to S_REBUILDING if re-indexing the entire workspace - - // for debugging - // TODO move this to Logger, as we have in SSE - static final boolean DEBUG; - private static JSPIndexManager fSingleton = null; - static long fTotalTime = 0; - private static final String PKEY_INDEX_STATE = "jspIndexState"; //$NON-NLS-1$ - - /** - * indexing job was canceled in the middle of it, index needs to be rebuilt - */ - public static final int S_CANCELED = 4; - - /** entire index is being rebuilt */ - public static final int S_REBUILDING = 3; - - // end class JSPResourceVisitor - - // the int '0' is reserved for the default value if a preference is not - // there - /** index is reliable to use */ - public static final int S_STABLE = 1; - - // end class ProcessFilesJob - - /** index is being updated (from a resource delta) */ - public static final int S_UPDATING = 2; - static { - String value = Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jspindexmanager"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - public synchronized static JSPIndexManager getInstance() { - - if (JSPIndexManager.fSingleton == null) { - JSPIndexManager.fSingleton = new JSPIndexManager(); - } - return JSPIndexManager.fSingleton; - } - - private IContentType fContentTypeJSP = null; - private JSPResourceVisitor fVisitor = null; - - private IndexWorkspaceJob indexingJob = new IndexWorkspaceJob(); - private IndexJobCoordinator indexJobCoordinator; - - private boolean initialized; - - private boolean initializing = true; - - private IResourceChangeListener jspResourceChangeListener; - - /** symbolic name for OSGI framework */ - private final String OSGI_FRAMEWORK_ID = "org.eclipse.osgi"; //$NON-NLS-1$ - - // Job for processing resource delta - private ProcessFilesJob processFilesJob = null; - - private JSPIndexManager() { - processFilesJob = new ProcessFilesJob(JSPCoreMessages.JSPIndexManager_0); - // only show in verbose mode - processFilesJob.setSystem(true); - processFilesJob.setPriority(Job.LONG); - processFilesJob.addJobChangeListener(new JobChangeAdapter() { - @Override - public void done(IJobChangeEvent event) { - super.done(event); - setStableState(); - } - }); - } - - /** - * A check to see if the OSGI framework is shutting down. - * - * @return true if the System Bundle is stopped (ie. the framework is - * shutting down) - */ - boolean frameworkIsShuttingDown() { - // in the Framework class there's a note: - // set the state of the System Bundle to STOPPING. - // this must be done first according to section 4.19.2 from the OSGi - // R3 spec. - boolean shuttingDown = Platform.getBundle(OSGI_FRAMEWORK_ID).getState() == Bundle.STOPPING; - if (JSPIndexManager.DEBUG && shuttingDown) { - System.out.println("JSPIndexManager: system is shutting down!"); //$NON-NLS-1$ - } - return shuttingDown; - } - - IndexWorkspaceJob getIndexingJob() { - return indexingJob; - } - - int getIndexState() { - return JSPCorePlugin.getDefault().getPluginPreferences().getInt(JSPIndexManager.PKEY_INDEX_STATE); - } - - IContentType getJspContentType() { - if (this.fContentTypeJSP == null) { - this.fContentTypeJSP = Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSP); - } - return this.fContentTypeJSP; - } - - ProcessFilesJob getProcessFilesJob() { - return processFilesJob; - } - - /** - * Package protected for access by inner Job class in resourceChanged(...) - * - * @return - */ - JSPResourceVisitor getVisitor() { - - if (this.fVisitor == null) { - this.fVisitor = new JSPResourceVisitor(); - } - return this.fVisitor; - } - - /** - * Creates and schedules a Job to process collected files. All JSP indexing - * should be done through this method or processFiles(IFile file) - * - * @param files - */ - final void indexFiles(IFile[] files) { - // don't use this rule - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=4931 - // processFiles.setRule(new IndexFileRule()); - processFilesJob.process(files); - } - - public void initialize() { - - JSPIndexManager singleInstance = JSPIndexManager.getInstance(); - - if (!singleInstance.initialized) { - singleInstance.initialized = true; - - singleInstance.indexJobCoordinator = new IndexJobCoordinator(); - singleInstance.jspResourceChangeListener = new JSPResourceChangeListener(); - - // added as JobChange listener so JSPIndexManager can be smarter - // about when it runs - Platform.getJobManager().addJobChangeListener(singleInstance.indexJobCoordinator); - - // add JSPIndexManager to keep JSP Index up to date - // listening for IResourceChangeEvent.PRE_DELETE and - // IResourceChangeEvent.POST_CHANGE - ResourcesPlugin.getWorkspace().addResourceChangeListener(jspResourceChangeListener, IResourceChangeEvent.POST_CHANGE); - - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=5091 - // makes sure IndexManager is aware of our indexes - saveIndexes(); - singleInstance.initializing = false; - - } - - } - - boolean isInitializing() { - return initializing; - } - - void rebuildIndex() { - - if (JSPIndexManager.DEBUG) { - System.out.println("*** JSP Index unstable, requesting re-indexing"); //$NON-NLS-1$ - } - - getIndexingJob().addJobChangeListener(new JobChangeAdapter() { - @Override - public void aboutToRun(IJobChangeEvent event) { - super.aboutToRun(event); - setRebuildingState(); - } - - @Override - public void done(IJobChangeEvent event) { - super.done(event); - setStableState(); - getIndexingJob().removeJobChangeListener(this); - } - }); - // we're about to reindex everything anyway - getProcessFilesJob().clearFiles(); - getIndexingJob().schedule(); - - } - - synchronized void rebuildIndexIfNeeded() { - if (getIndexState() != JSPIndexManager.S_STABLE) { - rebuildIndex(); - } - } - - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=5091 - // makes sure IndexManager is aware of our indexes - void saveIndexes() { - IndexManager indexManager = JavaModelManager.getJavaModelManager().getIndexManager(); - IPath jspModelWorkingLocation = JSPSearchSupport.getInstance().getModelJspPluginWorkingLocation(); - - File folder = new File(jspModelWorkingLocation.toOSString()); - String[] files = folder.list(); - String locay = ""; //$NON-NLS-1$ - Index index = null; - try { - for (int i = 0; i < files.length; i++) { - if (files[i].toLowerCase().endsWith(".index")) { //$NON-NLS-1$ - locay = jspModelWorkingLocation.toString() + "/" + files[i]; //$NON-NLS-1$ - // reuse index file - index = new Index(locay, "Index for " + locay, true); //$NON-NLS-1$ - indexManager.saveIndex(index); - } - } - } catch (Exception e) { - // we should be shutting down, want to shut down quietly - if (JSPIndexManager.DEBUG) { - e.printStackTrace(); - } - } - } - - void setCanceledState() { - setIndexState(JSPIndexManager.S_CANCELED); - } - - synchronized void setIndexState(int state) { - if (JSPIndexManager.DEBUG) { - System.out.println("JSPIndexManager setting index state to: " + state2String(state)); //$NON-NLS-1$ - } - Plugin jspModelPlugin = JSPCorePlugin.getDefault(); - jspModelPlugin.getPluginPreferences().setValue(JSPIndexManager.PKEY_INDEX_STATE, state); - jspModelPlugin.savePluginPreferences(); - - } - - void setRebuildingState() { - setIndexState(JSPIndexManager.S_REBUILDING); - } - - void setStableState() { - // if (getIndexState() != S_CANCELED) - setIndexState(JSPIndexManager.S_STABLE); - } - - void setUpdatingState() { - // if (getIndexState() != S_CANCELED) - setIndexState(JSPIndexManager.S_UPDATING); - } - - public void shutdown() { - - // stop listening - ResourcesPlugin.getWorkspace().removeResourceChangeListener(jspResourceChangeListener); - - // stop any searching - JSPSearchSupport.getInstance().setCanceled(true); - - // stop listening to jobs - Platform.getJobManager().removeJobChangeListener(indexJobCoordinator); - - int maxwait = 5000; - if (processFilesJob != null) { - processFilesJob.cancel(); - } - // attempt to make sure this indexing job is litterally - // done before continuing, since we are shutting down - waitTillNotRunning(maxwait, processFilesJob); - - if (indexingJob != null) { - indexingJob.cancel(); - } - waitTillNotRunning(maxwait, processFilesJob); - } - - private String state2String(int state) { - String s = "UNKNOWN"; //$NON-NLS-1$ - switch (state) { - case (JSPIndexManager.S_STABLE): - s = "S_STABLE"; //$NON-NLS-1$ - break; - case (JSPIndexManager.S_UPDATING): - s = "S_UPDATING"; //$NON-NLS-1$ - break; - case (JSPIndexManager.S_CANCELED): - s = "S_CANCELED"; //$NON-NLS-1$ - break; - case (JSPIndexManager.S_REBUILDING): - s = "S_REBUILDING"; //$NON-NLS-1$ - break; - } - return s; - } - - private void waitTillNotRunning(int maxSeconds, Job job) { - int pauseTime = 10; - int maxtries = maxSeconds / pauseTime; - int count = 0; - while (count++ < maxtries && job.getState() == Job.RUNNING) { - try { - Thread.sleep(pauseTime); - // System.out.println("count: " + count + " max: " + - // maxtries); - } catch (InterruptedException e) { - Logger.logException(e); - } - } - } - -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPPathIndexer.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPPathIndexer.java deleted file mode 100644 index 02643cf998..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPPathIndexer.java +++ /dev/null @@ -1,110 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java.search; - -import java.util.HashMap; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceProxy; -import org.eclipse.core.resources.IResourceProxyVisitor; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.wst.jsdt.core.search.IJavaSearchScope; -import org.eclipse.wst.jsdt.core.search.SearchPattern; -import org.eclipse.wst.jsdt.web.core.internal.provisional.contenttype.ContentTypeIdForJSP; - -/** - * pa_TODO Still need to take into consideration: - focus in workspace - search - * pattern - * - * @author pavery - */ -public class JSPPathIndexer { - - // visitor that retrieves jsp project paths for all jsp files in the - // workspace - class JSPFileVisitor implements IResourceProxyVisitor { - // hash map forces only one of each file - private HashMap fPaths = new HashMap(); - SearchPattern fPattern = null; - IJavaSearchScope fScope = null; - - public JSPFileVisitor(SearchPattern pattern, IJavaSearchScope scope) { - this.fPattern = pattern; - this.fScope = scope; - } - - public IPath[] getPaths() { - return (IPath[]) fPaths.values().toArray(new IPath[fPaths.size()]); - } - - public boolean visit(IResourceProxy proxy) throws CoreException { - - if (JSPSearchSupport.getInstance().isCanceled()) { - return false; - } - - if (proxy.getType() == IResource.FILE) { - - IContentType contentTypeJSP = Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSP); - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=3553 - // check this before description - // check name before actually getting the file (less work) - if (contentTypeJSP.isAssociatedWith(proxy.getName())) { - - IFile file = (IFile) proxy.requestResource(); - IContentDescription contentDescription = file.getContentDescription(); - String ctId = null; - if (contentDescription != null) { - ctId = contentDescription.getContentType().getId(); - } - if (ContentTypeIdForJSP.ContentTypeID_JSP.equals(ctId)) { - if (this.fScope.encloses(proxy.requestFullPath().toString())) { - - if (JSPPathIndexer.DEBUG) { - System.out.println("adding selected index path:" + file.getParent().getFullPath()); //$NON-NLS-1$ - } - - fPaths.put(file.getParent().getFullPath(), JSPSearchSupport.getInstance().computeIndexLocation(file.getParent().getFullPath())); - } - } - } - // don't search deeper for files - return false; - } - return true; - } - } - - // for debugging - static final boolean DEBUG; - - static { - String value = Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jspsearch"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - public IPath[] getVisibleJspPaths(SearchPattern pattern, IJavaSearchScope scope) { - - JSPFileVisitor jspFileVisitor = new JSPFileVisitor(pattern, scope); - try { - ResourcesPlugin.getWorkspace().getRoot().accept(jspFileVisitor, 0); - } catch (CoreException e) { - e.printStackTrace(); - } - return jspFileVisitor.getPaths(); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchDocument.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchDocument.java deleted file mode 100644 index 7397464514..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchDocument.java +++ /dev/null @@ -1,253 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java.search; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; - -import org.eclipse.core.resources.IFile; -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.core.runtime.Path; -import org.eclipse.jface.text.Position; -import org.eclipse.wst.jsdt.core.search.SearchParticipant; -import org.eclipse.wst.jsdt.web.core.internal.Logger; -import org.eclipse.wst.jsdt.web.core.internal.java.IJSPTranslation; -import org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation; -import org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslationAdapter; -import org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslationAdapterFactory; -import org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslationExtension; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.exceptions.UnsupportedCharsetExceptionWithDetail; -import org.eclipse.wst.sse.core.internal.provisional.IModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel; - -/** - * Created with a .jsp file, but should appear to be a .java file for indexing - * and searching purposes. There are purposely few fields in this class, and - * those fields are lightweight since it's possible for many JSP search - * documents to exist in memory at one time (eg. after importing a project with - * a large number of JSP files) - * - * @author pavery - */ -public class JSPSearchDocument { - - private char[] fCachedCharContents; - private long fLastModifiedStamp; - private SearchParticipant fParticipant = null; - private String UNKNOWN_PATH = "**path unknown**"; //$NON-NLS-1$ - private String fCUPath = UNKNOWN_PATH; - private String fJSPPathString = UNKNOWN_PATH; - /** - * @param file - * @param participant - * @throws CoreException - */ - public JSPSearchDocument(String filePath, SearchParticipant participant) { - - this.fJSPPathString = filePath; - this.fParticipant = participant; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.core.search.SearchDocument#getByteContents() - */ - public byte[] getByteContents() { - // TODO Auto-generated method stub - return null; - } - - /** - * @see org.eclipse.wst.jsdt.core.search.SearchDocument#getCharContents() - */ - public char[] getCharContents() { - - if (fCachedCharContents == null || isDirty()) { - JSPTranslation trans = getJSPTranslation(); - fCachedCharContents = trans != null ? trans.getJavaText().toCharArray() : new char[0]; - fCUPath = trans.getJavaPath(); - } - return fCachedCharContents; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.wst.jsdt.core.search.SearchDocument#getEncoding() - */ - public String getEncoding() { - // TODO Auto-generated method stub - return null; - } - - public IFile getFile() { - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IPath jspPath = new Path(this.fJSPPathString); - IFile jspFile = root.getFile(jspPath); - if (!jspFile.exists()) { - // possibly outside workspace - jspFile = root.getFileForLocation(jspPath); - } - return jspFile; - } - - public String getJavaText() { - return new String(getCharContents()); - } - - public int getJspOffset(int javaOffset) { - // copied from JSPTranslation - int result = -1; - int offsetInRange = 0; - Position jspPos, javaPos = null; - JSPTranslation trans = getJSPTranslation(); - if (trans != null) { - HashMap java2jspMap = trans.getJava2JspMap(); - - // iterate all mapped java ranges - Iterator it = java2jspMap.keySet().iterator(); - while (it.hasNext()) { - javaPos = (Position) it.next(); - // need to count the last position as included - if (!javaPos.includes(javaOffset) && !(javaPos.offset + javaPos.length == javaOffset)) { - continue; - } - - offsetInRange = javaOffset - javaPos.offset; - jspPos = (Position) java2jspMap.get(javaPos); - - if (jspPos != null) { - result = jspPos.offset + offsetInRange; - } else { - Logger.log(Logger.ERROR, "jspPosition was null!" + javaOffset); //$NON-NLS-1$ - } - break; - } - } - return result; - } - - /** - * It's not recommended for clients to hold on to this JSPTranslation since - * it's kind of large. If possible, hold on to the JSPSearchDocument, which - * is more of a lightweight proxy. - * - * @return the JSPTranslation for the jsp file, or null if it's an - * unsupported file. - */ - public final JSPTranslationExtension getJSPTranslation() { - JSPTranslationExtension translation = null; - IFile jspFile = getFile(); - if (!JSPSearchSupport.isJsp(jspFile)) { - return translation; - } - - IStructuredModel model = null; - try { - // get existing model for read, then get document from it - IModelManager modelManager = getModelManager(); - if (modelManager != null) { - model = modelManager.getModelForRead(jspFile); - } - // handle unsupported - if (model instanceof IDOMModel) { - IDOMModel xmlModel = (IDOMModel) model; - setupAdapterFactory(xmlModel); - IDOMDocument doc = xmlModel.getDocument(); - JSPTranslationAdapter adapter = (JSPTranslationAdapter) doc.getAdapterFor(IJSPTranslation.class); - translation = adapter.getJSPTranslation(); - } - } catch (IOException e) { - Logger.logException(e); - } catch (CoreException e) { - Logger.logException(e); - } catch (UnsupportedCharsetExceptionWithDetail e) { - // no need to log this. Just consider it an invalid file for our - // purposes. - // Logger.logException(e); - } finally { - if (model != null) { - model.releaseFromRead(); - } - } - return translation; - } - - private IModelManager getModelManager() { - return StructuredModelManager.getModelManager(); - } - - public SearchParticipant getParticipant() { - return this.fParticipant; - } - - /** - * the path to the Java compilation unit - * - * @see org.eclipse.wst.jsdt.core.search.SearchDocument#getPath() - */ - public String getPath() { - // caching the path since it's expensive to get translation - // important that isDirty() check is second to cache modification stamp - if (this.fCUPath == null || isDirty() || this.fCUPath == UNKNOWN_PATH) { - JSPTranslation trans = getJSPTranslation(); - if (trans != null) { - this.fCUPath = trans.getJavaPath(); - // save since it's expensive to calculate again later - fCachedCharContents = trans.getJavaText().toCharArray(); - } - } - return fCUPath != null ? fCUPath : UNKNOWN_PATH; - } - - private boolean isDirty() { - boolean modified = false; - IFile f = getFile(); - if (f != null) { - long currentStamp = f.getModificationStamp(); - if (currentStamp != fLastModifiedStamp) { - modified = true; - } - fLastModifiedStamp = currentStamp; - } - return modified; - } - - public void release() { - // nothing to do now since JSPTranslation is created on the fly - } - - /** - * add the factory for JSPTranslationAdapter here - * - * @param sm - */ - private void setupAdapterFactory(IStructuredModel sm) { - JSPTranslationAdapterFactory factory = new JSPTranslationAdapterFactory(); - sm.getFactoryRegistry().addFactory(factory); - } - - /** - * for debugging - */ - @Override - public String toString() { - return "[JSPSearchDocument:" + this.fJSPPathString + "]"; //$NON-NLS-1$ //$NON-NLS-2$ - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchParticipant.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchParticipant.java deleted file mode 100644 index 5e77f33045..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchParticipant.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java.search; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Platform; -import org.eclipse.wst.jsdt.core.search.IJavaSearchScope; -import org.eclipse.wst.jsdt.core.search.SearchDocument; -import org.eclipse.wst.jsdt.core.search.SearchEngine; -import org.eclipse.wst.jsdt.core.search.SearchParticipant; -import org.eclipse.wst.jsdt.core.search.SearchPattern; -import org.eclipse.wst.jsdt.core.search.SearchRequestor; - -/** - * Integration of JSP w/ java search. - * - * @author pavery - */ -public class JSPSearchParticipant extends SearchParticipant { - - // for debugging - private static final boolean DEBUG = JSPSearchParticipant.calculateValue(); - - private static boolean calculateValue() { - String value = Platform.getDebugOption("org.eclipse.jstd.jsp.core/debug/jspsearch"); //$NON-NLS-1$ - boolean debug = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - return debug; - } - - @Override - public String getDescription() { - return "JSP"; //$NON-NLS-1$ - } - - /** - * @see org.eclipse.wst.jsdt.core.search.SearchParticipant#getDocument(org.eclipse.core.resources.IFile) - */ - public SearchDocument getDocument(IFile file) { - // never gets called? - return null; - } - - /** - * Important to never return null here or else Java search participation - * will break. - */ - @Override - public SearchDocument getDocument(String documentPath) { - SearchDocument sDoc = JSPSearchSupport.getInstance().getSearchDocument(documentPath); - - if (sDoc == null) { - // return a dummy doc here so search participation doesn't break - return new NullSearchDocument(documentPath); - } - return sDoc; - } - - @Override - public void indexDocument(SearchDocument document, IPath indexPath) { - if (!(document instanceof JavaSearchDocumentDelegate)) { - return; - } - - // use Java search indexing - SearchEngine.getDefaultSearchParticipant().indexDocument(document, indexPath); - } - - @Override - public void locateMatches(SearchDocument[] indexMatches, SearchPattern pattern, IJavaSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { - - if (monitor != null && monitor.isCanceled()) { - return; - } - - // filter out null matches - List filtered = new ArrayList(); - SearchDocument match = null; - for (int i = 0; i < indexMatches.length; i++) { - if (JSPSearchParticipant.DEBUG) { - System.out.println("found possible matching JavaSearchDocumentDelegate: " + indexMatches[i]); //$NON-NLS-1$ - } - match = indexMatches[i]; - if (match != null) { - // some matches may be null, or if the index is out of date, - // the file may not even exist - if (match instanceof JavaSearchDocumentDelegate && ((JavaSearchDocumentDelegate) match).getFile().exists()) { - filtered.add(match); - } - } - } - - indexMatches = (SearchDocument[]) filtered.toArray(new SearchDocument[filtered.size()]); - SearchEngine.getDefaultSearchParticipant().locateMatches(indexMatches, pattern, scope, requestor, monitor); - } - - @Override - public IPath[] selectIndexes(SearchPattern pattern, IJavaSearchScope scope) { - JSPPathIndexer indexer = new JSPPathIndexer(); - return indexer.getVisibleJspPaths(pattern, scope); - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchScope.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchScope.java deleted file mode 100644 index 0d960e1400..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchScope.java +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java.search; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.eclipse.core.resources.IResourceProxy; -import org.eclipse.core.runtime.IPath; -import org.eclipse.wst.jsdt.core.IJavaElement; -import org.eclipse.wst.jsdt.core.search.IJavaSearchScope; - -/** - * Used to constrain JSP/java search to certain paths and elements. - * - * @author pavery - */ -public class JSPSearchScope implements IJavaSearchScope { - - private boolean fEnclosesAll = false; - private List fJavaElements = null; - private List fResourcePaths = null; - - public JSPSearchScope() { - // empty constructor just returns true for everything - // everything is in scope - this.fEnclosesAll = true; - init(); - } - - public JSPSearchScope(IJavaElement[] javaElement) { - init(); - fJavaElements.addAll(Arrays.asList(javaElement)); - } - - public JSPSearchScope(String[] resourceStringPath) { - init(); - fResourcePaths.addAll(Arrays.asList(resourceStringPath)); - } - - public void addElement(IJavaElement element) { - this.fJavaElements.add(element); - } - - public void addPath(String path) { - this.fResourcePaths.add(path); - } - - public boolean encloses(IJavaElement element) { - - // pa_TOD implement - if (this.fEnclosesAll) { - return true; - } - - return true; - } - - public boolean encloses(IResourceProxy element) { - - if (this.fEnclosesAll) { - return true; - } else if (enclosesPath(element.requestFullPath().toOSString())) { - return true; - } - - return true; - } - - public boolean encloses(String resourcePathString) { - - if (this.fEnclosesAll) { - return true; - } else if (enclosesPath(resourcePathString)) { - return true; - } - - return false; - } - - private boolean enclosesPath(String possible) { - - String[] paths = (String[]) fResourcePaths.toArray(new String[fResourcePaths.size()]); - for (int i = 0; i < paths.length; i++) { - if (possible.equals(paths[i])) { - return true; - } - } - return false; - } - - public IPath[] enclosingProjectsAndJars() { - - // pa_TODO - return null; - } - - public String getDescription() { - - return "JSPSearchScope"; //$NON-NLS-1$ - } - - public boolean includesBinaries() { - return false; - } - - public boolean includesClasspaths() { - return false; - } - - private void init() { - this.fResourcePaths = new ArrayList(); - this.fJavaElements = new ArrayList(); - } - - public void setIncludesBinaries(boolean includesBinaries) { - // do nothing - } - - public void setIncludesClasspaths(boolean includesClasspaths) { - // do nothing - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchSupport.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchSupport.java deleted file mode 100644 index 4ec23d9c34..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JSPSearchSupport.java +++ /dev/null @@ -1,577 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java.search; - -import java.io.File; -import java.util.zip.CRC32; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.wst.jsdt.core.IJavaElement; -import org.eclipse.wst.jsdt.core.search.IJavaSearchConstants; -import org.eclipse.wst.jsdt.core.search.IJavaSearchScope; -import org.eclipse.wst.jsdt.core.search.SearchDocument; -import org.eclipse.wst.jsdt.core.search.SearchEngine; -import org.eclipse.wst.jsdt.core.search.SearchPattern; -import org.eclipse.wst.jsdt.core.search.SearchRequestor; -import org.eclipse.wst.jsdt.internal.core.JavaModelManager; -import org.eclipse.wst.jsdt.web.core.internal.JSPCoreMessages; -import org.eclipse.wst.jsdt.web.core.internal.JSPCorePlugin; -import org.eclipse.wst.jsdt.web.core.internal.Logger; -import org.eclipse.wst.jsdt.web.core.internal.java.JSP2ServletNameUtil; -import org.eclipse.wst.jsdt.web.core.internal.provisional.contenttype.ContentTypeIdForJSP; - -/** - * Central access to java indexing and search. All contact between JDT indexing - * and Searching should be done through here. - * - * Clients should access the methods of this class via the single instance via - * <code>getInstance()</code>. - * - * @author pavery - */ -public class JSPSearchSupport { - - /** - * This operation ensures that the live resource's search markers show up in - * the open editor. It also allows the ability to pass in a ProgressMonitor - */ - private class SearchJob extends Job implements IJavaSearchConstants { - - IJavaElement fElement = null; - - boolean fIsCaseSensitive = false; - - int fLimitTo = IJavaSearchConstants.ALL_OCCURRENCES; - - int fMatchMode = SearchPattern.R_PATTERN_MATCH; - - SearchRequestor fRequestor = null; - - IJavaSearchScope fScope = null; - - int fSearchFor = IJavaSearchConstants.FIELD; - - String fSearchText = ""; //$NON-NLS-1$ - - // constructor w/ java element - public SearchJob(IJavaElement element, IJavaSearchScope scope, SearchRequestor requestor) { - - super(JSPCoreMessages.JSP_Search + element.getElementName()); - this.fElement = element; - this.fScope = scope; - this.fRequestor = requestor; - } - - // constructor w/ search text - public SearchJob(String searchText, IJavaSearchScope scope, int searchFor, int limitTo, int matchMode, boolean isCaseSensitive, - SearchRequestor requestor) { - - super(JSPCoreMessages.JSP_Search + searchText); - this.fSearchText = searchText; - this.fScope = scope; - this.fSearchFor = searchFor; - this.fLimitTo = limitTo; - this.fMatchMode = matchMode; - this.fIsCaseSensitive = isCaseSensitive; - this.fRequestor = requestor; - } - - @Override - public IStatus run(IProgressMonitor jobMonitor) { - - if (jobMonitor != null && jobMonitor.isCanceled()) { - return Status.CANCEL_STATUS; - } - if (JSPSearchSupport.getInstance().isCanceled()) { - return Status.CANCEL_STATUS; - } - - SearchPattern javaSearchPattern = null; - // if an element is available, use that to create search pattern - // (eg. LocalVariable) - // otherwise use the text and other paramters - if (this.fElement != null) { - javaSearchPattern = SearchPattern.createPattern(this.fElement, this.fLimitTo); - } else { - javaSearchPattern = SearchPattern.createPattern(this.fSearchText, this.fSearchFor, this.fLimitTo, this.fMatchMode); - } - - if (javaSearchPattern != null) { - JSPSearchParticipant[] participants = { getSearchParticipant() }; - SearchEngine engine = new SearchEngine(); - try { - if (jobMonitor != null) { - jobMonitor.beginTask("", IProgressMonitor.UNKNOWN); //$NON-NLS-1$ - } - engine.search(javaSearchPattern, participants, this.fScope, this.fRequestor, jobMonitor); - } catch (CoreException e) { - if (JSPSearchSupport.DEBUG) { - Logger.logException(e); - } - } - // non-CoreExceptions will permanently stall the Worker thread - catch (Exception e) { - if (JSPSearchSupport.DEBUG) { - Logger.logException(e); - } - } finally { - if (jobMonitor != null) { - jobMonitor.done(); - } - } - } - return Status.OK_STATUS; - } - } - - // end SearchJob - /** - * Runnable forces caller to wait until finished (as opposed to using a Job) - */ - private class SearchRunnable implements IWorkspaceRunnable, IJavaSearchConstants { - - IJavaElement fElement = null; - - boolean fIsCaseSensitive = false; - - int fLimitTo = IJavaSearchConstants.ALL_OCCURRENCES; - - int fMatchMode = SearchPattern.R_PATTERN_MATCH; - - SearchRequestor fRequestor = null; - - IJavaSearchScope fScope = null; - - int fSearchFor = IJavaSearchConstants.FIELD; - - String fSearchText = ""; //$NON-NLS-1$ - - // constructor w/ java element - public SearchRunnable(IJavaElement element, IJavaSearchScope scope, SearchRequestor requestor) { - - this.fElement = element; - this.fScope = scope; - this.fRequestor = requestor; - } - - // constructor w/ search text - public SearchRunnable(String searchText, IJavaSearchScope scope, int searchFor, int limitTo, int matchMode, boolean isCaseSensitive, - SearchRequestor requestor) { - - this.fSearchText = searchText; - this.fScope = scope; - this.fSearchFor = searchFor; - this.fLimitTo = limitTo; - this.fMatchMode = matchMode; - this.fIsCaseSensitive = isCaseSensitive; - this.fRequestor = requestor; - } - - public void run(IProgressMonitor monitor) throws CoreException { - - if (monitor != null && monitor.isCanceled()) { - return; - } - if (JSPSearchSupport.getInstance().isCanceled()) { - return; - } - - SearchPattern javaSearchPattern = null; - // if an element is available, use that to create search pattern - // (eg. LocalVariable) - // otherwise use the text and other paramters - if (this.fElement != null) { - javaSearchPattern = SearchPattern.createPattern(this.fElement, fLimitTo); - } else { - javaSearchPattern = SearchPattern.createPattern(fSearchText, fSearchFor, fLimitTo, fMatchMode); - } - - if (javaSearchPattern != null) { - JSPSearchParticipant[] participants = { getSearchParticipant() }; - SearchEngine engine = new SearchEngine(); - try { - if (monitor != null) { - monitor.beginTask("", 0); //$NON-NLS-1$ - } - engine.search(javaSearchPattern, participants, fScope, fRequestor, monitor); - } catch (CoreException e) { - Logger.logException(e); - // throw e; - } - // non-CoreExceptions will permanently stall the Worker thread - catch (Exception e) { - Logger.logException(e); - } finally { - if (monitor != null) { - monitor.done(); - } - } - } - } - } - - // for debugging - static final boolean DEBUG; - - private static JSPSearchSupport singleton = null; - - static { - String value = Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jspsearch"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - /** - * Clients should access the methods of this class via the single instance - * via getInstance() - * - * @return - */ - public synchronized static JSPSearchSupport getInstance() { - - if (JSPSearchSupport.singleton == null) { - JSPSearchSupport.singleton = new JSPSearchSupport(); - } - return JSPSearchSupport.singleton; - } - - /** - * Utility method to check if a file is a jsp file (since this is done - * frequently) - */ - public static boolean isJsp(IFile file) { - // (pa) 20051025 removing deep content type check - // because this method is called frequently - // and IO is expensive - boolean isJsp = false; - - if (file != null && file.exists()) { - - IContentType contentTypeJSP = Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSP); - // check this before description, it's less expensive - if (contentTypeJSP.isAssociatedWith(file.getName())) { - isJsp = true; - } - } - - return isJsp; - } - - // pa_TODO may be slow (esp for indexing entire workspace) - private final CRC32 fChecksumCalculator = new CRC32(); - - private IPath fJspPluginLocation = null; - - /** main cancel montior for all search support */ - private final IProgressMonitor fMonitor = new NullProgressMonitor(); - - // end SearchRunnable - - private JSPSearchParticipant fParticipant = null; - - private JSPSearchSupport() { - // force use of single instance - } - - /** - * schedules a search document representing this JSP file for indexing (by - * the java indexer) - * - * @param file - * the JSP file - * @return true if indexing was successful, false otherwise - * @throws CoreException - */ - public SearchDocument addJspFile(IFile file) { - if (JSPSearchSupport.getInstance().isCanceled() || !file.isAccessible()) { - return null; - } - - if (JSPSearchSupport.DEBUG) { - System.out.println("adding JSP file:" + file.getFullPath()); //$NON-NLS-1$ - } - - // create - SearchDocument delegate = createSearchDocument(file); - // null if not a jsp file - if (delegate != null) { - try { - getSearchParticipant().scheduleDocumentIndexing(delegate, computeIndexLocation(file.getParent().getFullPath())); - } catch (Exception e) { - // ensure that failure here doesn't keep other documents from - // being indexed - // if peformed in a batch call (like JSPIndexManager) - if (JSPSearchSupport.DEBUG) { - e.printStackTrace(); - } - } - } - - if (JSPSearchSupport.DEBUG) { - System.out.println("scheduled" + delegate + "for indexing"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - return delegate; - } - - // This is called from JSPPathIndexer - // pa_TODO - // how can we make sure participant indexLocations are updated at startup? - public final IPath computeIndexLocation(IPath containerPath) { - - String indexLocation = null; - // we don't want to inadvertently use a JDT Index - // we want to be sure to use the Index from the JSP location - // Object obj = indexLocations.get(containerPath); - // if (obj != null) { - // indexLocation = (String) obj; - // } else { - // create index entry - String pathString = containerPath.toOSString(); - this.fChecksumCalculator.reset(); - this.fChecksumCalculator.update(pathString.getBytes()); - String fileName = Long.toString(this.fChecksumCalculator.getValue()) + ".index"; //$NON-NLS-1$ - // this is the only difference from - // IndexManager#computeIndexLocation(...) - indexLocation = getModelJspPluginWorkingLocation().append(fileName).toOSString(); - - // pa_TODO need to add to java path too, so JDT search support knows - // there should be a non internal way to do this. - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=77564 - JavaModelManager.getJavaModelManager().getIndexManager().indexLocations.put(containerPath, indexLocation); - // } - return new Path(indexLocation); - } - - /** - * @param jspFile - * @return SearchDocument if the file is not null, exists, and is a JSP - * file, otherwise null. - */ - private SearchDocument createSearchDocument(IFile jspFile) { - - JavaSearchDocumentDelegate delegate = null; - if (jspFile != null && jspFile.exists() && JSPSearchSupport.isJsp(jspFile)) { - - delegate = new JavaSearchDocumentDelegate(new JSPSearchDocument(jspFile.getFullPath().toString(), getSearchParticipant())); - } - return delegate; - - } - - /** - * Unmangles the searchDocPath and returns the corresponding JSP file. - * - * @param searchDocPath - */ - private IFile fileForCUPath(String searchDocPath) { - - String[] split = searchDocPath.split("/"); //$NON-NLS-1$ - String classname = split[split.length - 1]; - - // ignore anything but .java matches (like .class binary matches) - if (!searchDocPath.endsWith(".java")) { //$NON-NLS-1$ - return null; - } - - String filePath = JSP2ServletNameUtil.unmangle(classname); - - // try absolute path - IFile f = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(new Path(filePath)); - // workspace relative then - if (f == null) { - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=86009 - // must have a project name as well - // which would mean >= 2 path segments - IPath path = new Path(filePath); - if (path.segmentCount() >= 2) { - f = ResourcesPlugin.getWorkspace().getRoot().getFile(path); - } - } - return f; - } - - // copied from JDT IndexManager - public IPath getModelJspPluginWorkingLocation() { - - if (this.fJspPluginLocation != null) { - return this.fJspPluginLocation; - } - - // Append the folder name "jspsearch" to keep the state location area - // cleaner - IPath stateLocation = JSPCorePlugin.getDefault().getStateLocation().append("jspsearch"); - - // pa_TODO workaround for - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=62267 - // copied from IndexManager - String device = stateLocation.getDevice(); - if (device != null && device.charAt(0) == '/') { - stateLocation = stateLocation.setDevice(device.substring(1)); - } - - // ensure that it exists on disk - File folder = new File(stateLocation.toOSString()); - if (!folder.isDirectory()) { - try { - folder.mkdir(); - } catch (SecurityException e) { - } - } - - return this.fJspPluginLocation = stateLocation; - } - - /** - * JSP Indexing and Search jobs check this - * - * @return - */ - public final IProgressMonitor getProgressMonitor() { - - return this.fMonitor; - } - - /** - * Centralized place to access JSPSearchDocuments (used by - * JSPSearchParticipant and JSPSearchRequestor) - * - * @param searchDocPath - * @param doc - * @return the JSPSearchDocument or null if one is not found - */ - public SearchDocument getSearchDocument(String searchDocPath) { - - SearchDocument delegate = null; - IFile f = fileForCUPath(searchDocPath); - if (f != null) { - delegate = createSearchDocument(f); - } else { - // handle failure case... (file deleted maybe?) - } - return delegate; - } - - JSPSearchParticipant getSearchParticipant() { - - if (this.fParticipant == null) { - this.fParticipant = new JSPSearchParticipant(); - } - return this.fParticipant; - } - - /** - * JSP Indexing and Search jobs check this - * - * @return - */ - public synchronized final boolean isCanceled() { - - return fMonitor.isCanceled(); - } - - /** - * Search for an IJavaElement, constrained by the given parameters. Runs in - * a background Job (results may still come in after this method call) - * - * @param element - * @param scope - * @param requestor - */ - public void search(IJavaElement element, IJavaSearchScope scope, SearchRequestor requestor) { - - JSPIndexManager.getInstance().rebuildIndexIfNeeded(); - - SearchJob job = new SearchJob(element, scope, requestor); - setCanceled(false); - job.setUser(true); - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=5032 - // job.setRule(ResourcesPlugin.getWorkspace().getRoot()); - job.schedule(); - } - - /** - * Perform a java search w/ the given parameters. Runs in a background Job - * (results may still come in after this method call) - * - * @param searchText - * the string of text to search on - * @param searchFor - * IJavaSearchConstants.TYPE, METHOD, FIELD, PACKAGE, etc... - * @param limitTo - * IJavaSearchConstants.DECLARATIONS, - * IJavaSearchConstants.REFERENCES, - * IJavaSearchConstants.IMPLEMENTORS, or - * IJavaSearchConstants.ALL_OCCURRENCES - * @param matchMode - * allow * wildcards or not - * @param isCaseSensitive - * @param requestor - * passed in to accept search matches (and do "something" with - * them) - */ - public void search(String searchText, IJavaSearchScope scope, int searchFor, int limitTo, int matchMode, boolean isCaseSensitive, SearchRequestor requestor) { - - JSPIndexManager.getInstance().rebuildIndexIfNeeded(); - - SearchJob job = new SearchJob(searchText, scope, searchFor, limitTo, matchMode, isCaseSensitive, requestor); - setCanceled(false); - job.setUser(true); - // https://w3.opensource.ibm.com/bugzilla/show_bug.cgi?id=5032 - // pops up user operation blocked dialog if you perform a long search, - // then open a file because it locks the workspace - // job.setRule(ResourcesPlugin.getWorkspace().getRoot()); - job.schedule(); - } - - /** - * Search for an IJavaElement, constrained by the given parameters. Runs in - * an IWorkspace runnable (results will be reported by the end of this - * method) - * - * @param element - * @param scope - * @param requestor - */ - public void searchRunnable(IJavaElement element, IJavaSearchScope scope, SearchRequestor requestor) { - - JSPIndexManager.getInstance().rebuildIndexIfNeeded(); - - SearchRunnable searchRunnable = new SearchRunnable(element, scope, requestor); - try { - setCanceled(false); - ResourcesPlugin.getWorkspace().run(searchRunnable, JSPSearchSupport.getInstance().getProgressMonitor()); - } catch (CoreException e) { - e.printStackTrace(); - } - } - - /** - * JSP Indexing and Search jobs check this - * - * @return - */ - public synchronized final void setCanceled(boolean cancel) { - // System.out.println("search support monitor" + fMonitor); - fMonitor.setCanceled(cancel); - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JavaSearchDocumentDelegate.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JavaSearchDocumentDelegate.java deleted file mode 100644 index 78abc88cd3..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/JavaSearchDocumentDelegate.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java.search; - -import org.eclipse.core.resources.IFile; -import org.eclipse.wst.jsdt.internal.core.search.JavaSearchDocument; -import org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslationExtension; - -/** - * Wrapper method to set getPath() path to be the path of the compilation unit - * for the jsp file. (since it's a final method, it needs to be set via - * constructor) - * - * @author pavery - */ - -/* Used to extend SearchDocument */ - -public class JavaSearchDocumentDelegate extends JavaSearchDocument { - - private JSPSearchDocument fJSPSearchDoc = null; - - public JavaSearchDocumentDelegate(JSPSearchDocument jspSearchDoc) { - - super(jspSearchDoc.getPath(), jspSearchDoc.getParticipant()); - this.fJSPSearchDoc = jspSearchDoc; - } - - @Override - public byte[] getByteContents() { - - return this.fJSPSearchDoc.getByteContents(); - } - - @Override - public char[] getCharContents() { - - return this.fJSPSearchDoc.getCharContents(); - } - - @Override - public String getEncoding() { - - return this.fJSPSearchDoc.getEncoding(); - } - - public IFile getFile() { - - return this.fJSPSearchDoc.getFile(); - } - - public String getJavaText() { - return this.fJSPSearchDoc.getJavaText(); - } - - public int getJspOffset(int javaOffset) { - - return this.fJSPSearchDoc.getJspOffset(javaOffset); - } - - public JSPTranslationExtension getJspTranslation() { - - return this.fJSPSearchDoc.getJSPTranslation(); - } - - public void release() { - this.fJSPSearchDoc.release(); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/NullSearchDocument.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/NullSearchDocument.java deleted file mode 100644 index 8a4d6dbe07..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/java/search/NullSearchDocument.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.java.search; - -import org.eclipse.wst.jsdt.core.search.SearchDocument; -import org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslator; - -/** - * An empty servlet, safe for Java search participation - * - * @author pavery - */ -public class NullSearchDocument extends SearchDocument { - - StringBuffer fEmptyServletBuffer = null; - - public NullSearchDocument(String documentPath) { - super(documentPath, new JSPSearchParticipant()); - this.fEmptyServletBuffer = new JSPTranslator().getEmptyTranslation(); - } - - @Override - public byte[] getByteContents() { - return this.fEmptyServletBuffer.toString().getBytes(); - } - - @Override - public char[] getCharContents() { - return this.fEmptyServletBuffer.toString().toCharArray(); - } - - @Override - public String getEncoding() { - return null; - } - -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/modelhandler/EmbeddedScript.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/modelhandler/EmbeddedScript.java deleted file mode 100644 index e88b848e0e..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/modelhandler/EmbeddedScript.java +++ /dev/null @@ -1,116 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.modelhandler; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.wst.html.core.internal.modelquery.ModelQueryAdapterFactoryForEmbeddedHTML; -import org.eclipse.wst.jsdt.web.core.internal.java.IJSPTranslation; -import org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslationAdapterFactory; -import org.eclipse.wst.sse.core.internal.ltk.modelhandler.EmbeddedTypeHandler; -import org.eclipse.wst.sse.core.internal.ltk.parser.JSPCapableParser; -import org.eclipse.wst.sse.core.internal.model.FactoryRegistry; -import org.eclipse.wst.sse.core.internal.provisional.INodeAdapterFactory; -import org.eclipse.wst.sse.core.internal.util.Assert; - -public class EmbeddedScript implements EmbeddedTypeHandler { - - static String AssociatedContentTypeID = "org.eclipse.wst.html.core.htmlsource"; //$NON-NLS-1$ - public String ContentTypeID_EmbeddedHTML = "org.eclipse.wst.html.core.internal.contenttype.EmbeddedHTML"; //$NON-NLS-1$ - private List supportedMimeTypes; - - /** - * Constructor for EmbeddedHTML. - */ - public EmbeddedScript() { - super(); - } - - public boolean canHandleMimeType(String mimeType) { - return getSupportedMimeTypes().contains(mimeType); - } - - /* - * Only "model side" embedded factories can be added here. - */ - public List getAdapterFactories() { - List factories = new ArrayList(); - factories.add(new ModelQueryAdapterFactoryForEmbeddedHTML()); - // factories.addAll(PluginContributedFactoryReader.getInstance().getFactories(this)); - return factories; - } - - /** - * @see EmbeddedContentType#getFamilyId() - */ - public String getFamilyId() { - return EmbeddedScript.AssociatedContentTypeID; - } - - public List getSupportedMimeTypes() { - if (supportedMimeTypes == null) { - supportedMimeTypes = new ArrayList(); - supportedMimeTypes.add("text/html"); //$NON-NLS-1$ - supportedMimeTypes.add("text/xhtml"); //$NON-NLS-1$ - supportedMimeTypes.add("application/xhtml+xml"); //$NON-NLS-1$ - supportedMimeTypes.add("text/vnd.wap.wml"); //$NON-NLS-1$ - } - return supportedMimeTypes; - } - - public void initializeFactoryRegistry(FactoryRegistry registry) { - Assert.isNotNull(registry); - INodeAdapterFactory factory = null; - factory = registry.getFactoryFor(IJSPTranslation.class); - if (factory == null) { - factory = new JSPTranslationAdapterFactory(); - registry.addFactory(factory); - } - - } - - /* - * @see EmbeddedContentType#initializeParser(RegionParser) - */ - public void initializeParser(JSPCapableParser parser) { - - } - - /** - * will someday be controlled via extension point - */ - public boolean isDefault() { - return true; - } - - public EmbeddedTypeHandler newInstance() { - return new EmbeddedScript(); - } - - public void uninitializeFactoryRegistry(FactoryRegistry registry) { - Assert.isNotNull(registry); - - // ISSUE: should these factories be released? Or just - // removed from this registry, because we are getting ready to - // re-add them? - INodeAdapterFactory factory = null; - if (!registry.contains(IJSPTranslation.class)) { - factory = registry.getFactoryFor(IJSPTranslation.class); - factory.release(); - registry.removeFactory(factory); - } - } - - public void uninitializeParser(JSPCapableParser parser) { - - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/modelhandler/EmbeddedTypeStateData.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/modelhandler/EmbeddedTypeStateData.java deleted file mode 100644 index ac1aa1b7f8..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/modelhandler/EmbeddedTypeStateData.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.modelhandler; - -import org.eclipse.wst.sse.core.internal.ltk.modelhandler.EmbeddedTypeHandler; - -/** - * This class is only for remembering old and new embedded handlers, in the - * event a re-init is needed. - */ -public class EmbeddedTypeStateData { - - EmbeddedTypeHandler newHandler; - EmbeddedTypeHandler oldHandler; - - public EmbeddedTypeStateData(EmbeddedTypeHandler oldHandler, EmbeddedTypeHandler newHandler) { - this.oldHandler = oldHandler; - this.newHandler = newHandler; - } - - public EmbeddedTypeHandler getNewHandler() { - return newHandler; - } - - public EmbeddedTypeHandler getOldHandler() { - return oldHandler; - } - -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/modelhandler/ModelHandlerForHTML.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/modelhandler/ModelHandlerForHTML.java deleted file mode 100644 index 060d768073..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/modelhandler/ModelHandlerForHTML.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.modelhandler; - -import org.eclipse.wst.html.core.internal.encoding.HTMLDocumentCharsetDetector; -import org.eclipse.wst.html.core.internal.encoding.HTMLDocumentLoader; -import org.eclipse.wst.html.core.internal.encoding.HTMLModelLoader; -import org.eclipse.wst.sse.core.internal.document.IDocumentCharsetDetector; -import org.eclipse.wst.sse.core.internal.document.IDocumentLoader; -import org.eclipse.wst.sse.core.internal.ltk.modelhandler.AbstractModelHandler; -import org.eclipse.wst.sse.core.internal.ltk.modelhandler.IModelHandler; -import org.eclipse.wst.sse.core.internal.provisional.IModelLoader; - -public class ModelHandlerForHTML extends AbstractModelHandler implements IModelHandler { - /** - * Needs to match what's in plugin registry. In fact, can be overwritten at - * run time with what's in registry! (so should never be 'final') - */ - static String AssociatedContentTypeID = "org.eclipse.wst.html.core.htmlsource"; //$NON-NLS-1$ - /** - * Needs to match what's in plugin registry. In fact, can be overwritten at - * run time with what's in registry! (so should never be 'final') - */ - private static String ModelHandlerID_HTML = "org.eclipse.wst.html.core.modelhandler"; //$NON-NLS-1$ - - public ModelHandlerForHTML() { - super(); - setId(ModelHandlerForHTML.ModelHandlerID_HTML); - setAssociatedContentTypeId(ModelHandlerForHTML.AssociatedContentTypeID); - } - - public IDocumentLoader getDocumentLoader() { - return new HTMLDocumentLoader(); - } - - @Override - public IDocumentCharsetDetector getEncodingDetector() { - return new HTMLDocumentCharsetDetector(); - } - - public IModelLoader getModelLoader() { - return new HTMLModelLoader(); - } - -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/preferences/JSPCorePreferenceInitializer.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/preferences/JSPCorePreferenceInitializer.java deleted file mode 100644 index 30e4a4d9a5..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/preferences/JSPCorePreferenceInitializer.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.wst.jsdt.web.core.internal.preferences; - -import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; -import org.eclipse.core.runtime.preferences.DefaultScope; -import org.eclipse.core.runtime.preferences.IEclipsePreferences; -import org.eclipse.wst.jsdt.web.core.internal.JSPCorePlugin; -import org.eclipse.wst.sse.core.internal.encoding.CommonCharsetNames; -import org.eclipse.wst.sse.core.internal.encoding.CommonEncodingPreferenceNames; - -/** - * Sets default values for JSP Core preferences - */ -public class JSPCorePreferenceInitializer extends AbstractPreferenceInitializer { - - @Override - public void initializeDefaultPreferences() { - IEclipsePreferences node = new DefaultScope().getNode(JSPCorePlugin.getDefault().getBundle().getSymbolicName()); - - // compiler/validation preferences - node.putBoolean(JSPCorePreferenceNames.VALIDATE_FRAGMENTS, true); - - // code generation preferences - node.put(CommonEncodingPreferenceNames.INPUT_CODESET, ""); //$NON-NLS-1$ - String defaultEnc = "ISO-8859-1";//$NON-NLS-1$ - String systemEnc = System.getProperty("file.encoding"); //$NON-NLS-1$ - if (systemEnc != null) { - defaultEnc = CommonCharsetNames.getPreferredDefaultIanaName(systemEnc, "ISO-8859-1");//$NON-NLS-1$ - } - node.put(CommonEncodingPreferenceNames.OUTPUT_CODESET, defaultEnc); - node.put(CommonEncodingPreferenceNames.END_OF_LINE_CODE, ""); //$NON-NLS-1$ - - // this could be made smarter by actually looking up the content - // type's valid extensions - node.put(JSPCorePreferenceNames.DEFAULT_EXTENSION, "html"); //$NON-NLS-1$ - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/preferences/JSPCorePreferenceNames.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/preferences/JSPCorePreferenceNames.java deleted file mode 100644 index cbdd008401..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/preferences/JSPCorePreferenceNames.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.jsdt.web.core.internal.preferences; - -/** - * Common preference keys used by JSP core - */ -public class JSPCorePreferenceNames { - /** - * The default extension to use when none is specified in the New JSP File - * Wizard. - * <p> - * Value is of type <code>String</code>. - * </p> - */ - public static final String DEFAULT_EXTENSION = "defaultExtension"; //$NON-NLS-1$ - - /** - * Indicates if JSP fragments should be compiled/validated. JSP fragments - * will be validated when true. - * <p> - * Value is of type <code>Boolean</code>. - * </p> - */ - public static final String VALIDATE_FRAGMENTS = "validateFragments"; //$NON-NLS-1$ - - private JSPCorePreferenceNames() { - // empty private constructor so users cannot instantiate class - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsNatureInstaller.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsNatureInstaller.java deleted file mode 100644 index b065dfe6a8..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsNatureInstaller.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.eclipse.wst.jsdt.web.core.internal.project; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.wst.common.project.facet.core.IDelegate; -import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion; -import org.eclipse.wst.jsdt.web.core.internal.JSPCorePlugin; - -public class JsNatureInstaller implements IDelegate { - - public void execute(IProject project, IProjectFacetVersion fv, Object config, IProgressMonitor monitor) throws CoreException { - if (monitor == null) { - monitor = new NullProgressMonitor(); - } - monitor.beginTask("Installing Facet for JavaScript Development Tools" + ".", 100); //$NON-NLS-1$ - try { - installNature(project, monitor); - } finally { - monitor.done(); - } - } - - public void installNature(IProject project, IProgressMonitor monitor) throws CoreException { - monitor.beginTask("Installing JavaScript Development Tools...", 100); - monitor.subTask("Adding JavaScript Development Toolkit Nature..."); - SubProgressMonitor sub = new SubProgressMonitor(monitor, 25); - - try { - monitor.worked(20); - JsWebNature jsNature = new JsWebNature(project, monitor); - monitor.worked(20); - jsNature.configure(); - monitor.worked(40); - - } catch (Exception e) { - throw new CoreException(new Status(IStatus.ERROR, JSPCorePlugin.PLUGIN_ID, IStatus.OK, "Error installing runtime! JavaScript Development Tools could not be added..", e)); - } - - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsNatureUninstaller.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsNatureUninstaller.java deleted file mode 100644 index f44faa6baa..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsNatureUninstaller.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.eclipse.wst.jsdt.web.core.internal.project; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IProjectNature; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.wst.common.project.facet.core.IDelegate; -import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion; -import org.eclipse.wst.jsdt.web.core.internal.JSPCorePlugin; - -public class JsNatureUninstaller implements IDelegate { - public void execute(IProject project, IProjectFacetVersion fv, Object config, IProgressMonitor monitor) throws CoreException { - - if (monitor == null) { - monitor = new NullProgressMonitor(); - } - - monitor.beginTask("Uninstalling Facet for JavaScript Development Tools" + ".", 100); //$NON-NLS-1$ - - try { - uninstallNature(project, monitor); - } finally { - monitor.done(); - } - - } - - public void uninstallNature(IProject project, IProgressMonitor monitor) throws CoreException { - - monitor.beginTask("Uninstalling JavaScript Development Tools...", 100); - - // by using natures we can leverage the precondition support - monitor.subTask("Removing JavaScript Development Toolking Nature..."); - SubProgressMonitor sub = new SubProgressMonitor(monitor, 25); - - if (!JsWebNature.hasJsNature(project)) { - return; - } - - try { - - IProjectNature jsNature = new JsWebNature(project, monitor); - monitor.worked(20); - monitor.worked(50); - jsNature.deconfigure(); - monitor.worked(20); - - } catch (CoreException e) { - throw new CoreException(new Status(IStatus.ERROR, JSPCorePlugin.PLUGIN_ID, IStatus.OK, "Error installing runtime! JavaScript Development Tools could not be removed, or is not present in target project..", e)); - } - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsWebNature.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsWebNature.java deleted file mode 100644 index 9d93106aef..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsWebNature.java +++ /dev/null @@ -1,241 +0,0 @@ -package org.eclipse.wst.jsdt.web.core.internal.project; - -import java.util.Arrays; -import java.util.Vector; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IProjectDescription; -import org.eclipse.core.resources.IProjectNature; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.OperationCanceledException; -import org.eclipse.wst.jsdt.core.IClasspathEntry; -import org.eclipse.wst.jsdt.core.JavaCore; -import org.eclipse.wst.jsdt.internal.core.JavaProject; -import org.eclipse.wst.jsdt.ui.PreferenceConstants; - -public class JsWebNature implements IProjectNature { - - private static final String FILENAME_CLASSPATH = ".classpath"; //$NON-NLS-1$ - - public static void addJsNature(IProject project, IProgressMonitor monitor) throws CoreException { - if (monitor != null && monitor.isCanceled()) { - throw new OperationCanceledException(); - } - if (!project.hasNature(JavaCore.NATURE_ID)) { - IProjectDescription description = project.getDescription(); - String[] prevNatures = description.getNatureIds(); - String[] newNatures = new String[prevNatures.length + 1]; - System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length); - newNatures[prevNatures.length] = JavaCore.NATURE_ID; - description.setNatureIds(newNatures); - project.setDescription(description, monitor); - } else { - if (monitor != null) { - monitor.worked(1); - } - } - } - - public static boolean hasJsNature(IProject project) { - boolean valid = false; - try { - valid = project.hasNature(JavaCore.NATURE_ID); - } catch (Exception e) { - } - - return valid; - } - - public static void removeJsNature(IProject project, IProgressMonitor monitor) throws CoreException { - if (monitor != null && monitor.isCanceled()) { - throw new OperationCanceledException(); - } - if (project.hasNature(JavaCore.NATURE_ID)) { - IProjectDescription description = project.getDescription(); - String[] prevNatures = description.getNatureIds(); - String[] newNatures = new String[prevNatures.length - 1]; - - int k = 0; - for (int i = 0; i < prevNatures.length; i++) { - if (prevNatures[i] != JavaCore.NATURE_ID) { - newNatures[k++] = prevNatures[i]; - } - } - description.setNatureIds(newNatures); - project.setDescription(description, monitor); - } else { - if (monitor != null) { - monitor.worked(1); - } - } - } - - private Vector classPathEntries = new Vector(); - private boolean DEBUG = false; - private IProject fCurrProject; - - private JavaProject fJavaProject; - - private IPath fOutputLocation; - - private IProgressMonitor monitor; - - public JsWebNature() { - monitor = new NullProgressMonitor(); - } - - public JsWebNature(IProject project, IProgressMonitor monitor) { - fCurrProject = project; - if (monitor != null) { - this.monitor = monitor; - } else { - monitor = new NullProgressMonitor(); - } - } - - public void configure() throws CoreException { - if (hasProjectClassPathFile()) { - IClasspathEntry[] entries = getRawClassPath(); - if (entries != null && entries.length > 0) { - classPathEntries.addAll(Arrays.asList(entries)); - } - } - initOutputPath(); - createSourceClassPath(); - initJREEntry(); - JsWebNature.addJsNature(fCurrProject, monitor); - fJavaProject = (JavaProject) JavaCore.create(fCurrProject); - fJavaProject.setProject(fCurrProject); - try { - // , fOutputLocation - if(!hasProjectClassPathFile() )fJavaProject.setRawClasspath((IClasspathEntry[]) classPathEntries.toArray(new IClasspathEntry[] {}), fOutputLocation, monitor); - if(hasProjectClassPathFile() )fJavaProject.setRawClasspath((IClasspathEntry[]) classPathEntries.toArray(new IClasspathEntry[] {}), monitor); - } catch (Exception e) { - System.out.println(e); - } - fCurrProject.refreshLocal(IResource.DEPTH_INFINITE, monitor); - } - - private void createSourceClassPath() { - if (hasAValidSourcePath()) { - return; - } - IPath projectPath = fCurrProject.getFullPath(); - classPathEntries.add(JavaCore.newSourceEntry(projectPath)); - } - - public void deconfigure() throws CoreException { - IClasspathEntry[] defaultJRELibrary = PreferenceConstants.getDefaultJRELibrary(); - IClasspathEntry[] entries = getRawClassPath(); - Vector goodEntries = new Vector(); - for (int i = 0; i < entries.length; i++) { - if (entries[i] != defaultJRELibrary[0]) { - goodEntries.add(entries[i]); - } - } - IPath outputLocation = getJavaProject().getOutputLocation(); - getJavaProject().setRawClasspath((IClasspathEntry[]) goodEntries.toArray(new IClasspathEntry[] {}), outputLocation, monitor); - getJavaProject().deconfigure(); - JsWebNature.removeJsNature(fCurrProject, monitor); - fCurrProject.refreshLocal(IResource.DEPTH_INFINITE, monitor); - } - - private IPath getCurrentOutputPath() { - IPath outputLocation = null; - - if (hasProjectClassPathFile()) { - try { - - - - System.out.println("Hello"); - } catch (Exception e) { - if (DEBUG) { - System.out.println("Error checking sourcepath:" + e); - } - } - } - return outputLocation; - } - - public JavaProject getJavaProject() { - - if (fJavaProject == null) { - fJavaProject = (JavaProject) JavaCore.create(fCurrProject); - fJavaProject.setProject(fCurrProject); - } - return fJavaProject; - } - - public IProject getProject() { - return this.fCurrProject; - } - - private IClasspathEntry[] getRawClassPath() { - JavaProject proj = new JavaProject(); - proj.setProject(fCurrProject); - return proj.readRawClasspath(); - } - - private boolean hasAValidSourcePath() { - if (hasProjectClassPathFile()) { - try { - - IClasspathEntry[] entries = getRawClassPath(); - for (int i = 0; i < entries.length; i++) { - if (entries[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) { - return true; - } - } - } catch (Exception e) { - if (DEBUG) { - System.out.println("Error checking sourcepath:" + e); - } - } - } - return false; - } - - private boolean hasProjectClassPathFile() { - if (fCurrProject == null) { - return false; - } - return fCurrProject.getFile(JsWebNature.FILENAME_CLASSPATH).exists(); - } - - private void initJREEntry() { - IClasspathEntry[] defaultJRELibrary = PreferenceConstants.getDefaultJRELibrary(); - try { - IClasspathEntry[] entries = getRawClassPath(); - for (int i = 0; i < entries.length; i++) { - if (entries[i] == defaultJRELibrary[0]) { - return; - } - } - classPathEntries.add(defaultJRELibrary[0]); - } catch (Exception e) { - if (DEBUG) { - System.out.println("Error checking sourcepath:" + e); - } - } - } - - private void initOutputPath() { - if (fOutputLocation == null) { - fOutputLocation = getCurrentOutputPath(); - } - if (fOutputLocation == null) { - fOutputLocation = fCurrProject.getFullPath(); - } - - } - - public void setProject(IProject project) { - this.fCurrProject = project; - } - -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/provisional/contenttype/ContentTypeIdForJSP.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/provisional/contenttype/ContentTypeIdForJSP.java deleted file mode 100644 index b1f8ef3c3b..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/provisional/contenttype/ContentTypeIdForJSP.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.provisional.contenttype; - -/** - * This class, with its one field, is a convience to provide compile-time safety - * when refering to a contentType ID. The value of the contenttype id field must - * match what is specified in plugin.xml file. - */ - -public class ContentTypeIdForJSP { - /** - * The value of the contenttype id field must match what is specified in - * plugin.xml file. Note: this value is intentially set with default - * protected method so it will not be inlined. - */ - public final static String ContentTypeID_JSP = ContentTypeIdForJSP.getConstantString(); - /** - * The value of the contenttype id field must match what is specified in - * plugin.xml file. Note: this value is intentially set with default - * protected method so it will not be inlined. - */ - public final static String ContentTypeID_JSPFRAGMENT = ContentTypeIdForJSP.getFragmentConstantString(); - - static String getConstantString() { - return "org.eclipse.wst.html.core.htmlsource"; //$NON-NLS-1$ - } - - static String getFragmentConstantString() { - return "org.eclipse.wst.html.core.htmlsource"; //$NON-NLS-1$ - } - - /** - * Don't allow instantiation. - */ - private ContentTypeIdForJSP() { - super(); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/provisional/contenttype/IContentDescriptionForJSP.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/provisional/contenttype/IContentDescriptionForJSP.java deleted file mode 100644 index 005e8278f0..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/provisional/contenttype/IContentDescriptionForJSP.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.provisional.contenttype; - -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.wst.sse.core.internal.encoding.ICodedResourcePlugin; - -public interface IContentDescriptionForJSP { - public final static QualifiedName CONTENT_FAMILY_ATTRIBUTE = new QualifiedName(ICodedResourcePlugin.ID, "contentFamilyAttribute"); //$NON-NLS-1$; - /** - * Extra properties as part of ContentDescription, if the content is JSP. - */ - public final static QualifiedName CONTENT_TYPE_ATTRIBUTE = new QualifiedName(ICodedResourcePlugin.ID, "contentTypeAttribute"); //$NON-NLS-1$ - public final static QualifiedName LANGUAGE_ATTRIBUTE = new QualifiedName(ICodedResourcePlugin.ID, "languageAttribute"); //$NON-NLS-1$ - -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/provisional/text/IJSPPartitionTypes.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/provisional/text/IJSPPartitionTypes.java deleted file mode 100644 index 192c3ccf5c..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/provisional/text/IJSPPartitionTypes.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.eclipse.wst.jsdt.web.core.internal.provisional.text; - -/** - * This interface is not intended to be implemented. It defines the partition - * types for JSP. Clients should reference the partition type Strings defined - * here directly. - * - * @deprecated use - * org.eclipse.wst.jsdt.web.core.internal.provisional.text.IJSPPartitions - */ -@Deprecated -public interface IJSPPartitionTypes { - - String JSP_COMMENT = "org.eclipse.wst.jsdt.web.JSP_COMMENT"; //$NON-NLS-1$ - String JSP_CONTENT_DELIMITER = IJSPPartitionTypes.JSP_SCRIPT_PREFIX + "DELIMITER"; //$NON-NLS-1$ - - String JSP_CONTENT_JAVA = IJSPPartitionTypes.JSP_SCRIPT_PREFIX + "JAVA"; //$NON-NLS-1$ - String JSP_CONTENT_JAVASCRIPT = IJSPPartitionTypes.JSP_SCRIPT_PREFIX + "JAVASCRIPT"; //$NON-NLS-1$ - String JSP_DEFAULT = "org.eclipse.wst.jsdt.web.DEFAULT_JSP"; //$NON-NLS-1$ - String JSP_DEFAULT_EL = IJSPPartitionTypes.JSP_SCRIPT_PREFIX + "JSP_EL"; //$NON-NLS-1$ - String JSP_DEFAULT_EL2 = IJSPPartitionTypes.JSP_SCRIPT_PREFIX + "JSP_EL2"; //$NON-NLS-1$ - String JSP_DIRECTIVE = "org.eclipse.wst.jsdt.web.JSP_DIRECTIVE"; //$NON-NLS-1$ - - String JSP_SCRIPT_PREFIX = "org.eclipse.wst.jsdt.web.SCRIPT."; //$NON-NLS-1$ -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/tasks/JSPFileTaskScanner.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/tasks/JSPFileTaskScanner.java deleted file mode 100644 index d0318473c0..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/tasks/JSPFileTaskScanner.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2004 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.jsdt.web.core.internal.tasks; - -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.xml.core.internal.tasks.XMLFileTaskScanner; - -public class JSPFileTaskScanner extends XMLFileTaskScanner { - @Override - protected boolean isCommentRegion(IStructuredDocumentRegion region, ITextRegion textRegion) { - return super.isCommentRegion(region, textRegion); - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/validation/JSPBatchValidator.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/validation/JSPBatchValidator.java deleted file mode 100644 index f00e098741..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/validation/JSPBatchValidator.java +++ /dev/null @@ -1,493 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.jsdt.web.core.internal.validation; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceProxy; -import org.eclipse.core.resources.IResourceProxyVisitor; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExecutableExtension; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.jobs.ISchedulingRule; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.osgi.util.NLS; -import org.eclipse.wst.jsdt.core.JavaCore; -import org.eclipse.wst.jsdt.web.core.internal.JSPCoreMessages; -import org.eclipse.wst.jsdt.web.core.internal.Logger; -import org.eclipse.wst.jsdt.web.core.internal.contentproperties.JSPFContentProperties; -import org.eclipse.wst.jsdt.web.core.internal.provisional.contenttype.ContentTypeIdForJSP; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.utils.StringUtils; -import org.eclipse.wst.validation.internal.ConfigurationManager; -import org.eclipse.wst.validation.internal.ProjectConfiguration; -import org.eclipse.wst.validation.internal.ValidationRegistryReader; -import org.eclipse.wst.validation.internal.core.Message; -import org.eclipse.wst.validation.internal.core.ValidationException; -import org.eclipse.wst.validation.internal.operations.IWorkbenchContext; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidationContext; -import org.eclipse.wst.validation.internal.provisional.core.IValidatorJob; - -/** - * Performs JSP validation tasks for batch validation. The individual validator - * classes will still be used for source validation. - */ -public final class JSPBatchValidator implements IValidatorJob, IExecutableExtension { - class JSPFileVisitor implements IResourceProxyVisitor { - - private List fFiles = new ArrayList(); - private IReporter fReporter = null; - - public JSPFileVisitor(IReporter reporter) { - fReporter = reporter; - } - - final IFile[] getFiles() { - return (IFile[]) fFiles.toArray(new IFile[fFiles.size()]); - } - - public boolean visit(IResourceProxy proxy) throws CoreException { - - // check validation - if (fReporter.isCancelled()) { - return false; - } - - if (proxy.getType() == IResource.FILE) { - - if (isJSPType(proxy.getName()) && proxy.isAccessible()) { - IFile file = (IFile) proxy.requestResource(); - if (JSPBatchValidator.DEBUG) { - System.out.println("(+) JSPValidator adding file: " + file.getName()); //$NON-NLS-1$ - } - fFiles.add(file); - - // don't search deeper for files - return false; - } - } - return true; - } - } - - class LocalizedMessage extends Message { - - private String _message = null; - - public LocalizedMessage(int severity, String messageText) { - this(severity, messageText, null); - } - - public LocalizedMessage(int severity, String messageText, IResource targetObject) { - this(severity, messageText, (Object) targetObject); - } - - public LocalizedMessage(int severity, String messageText, Object targetObject) { - super(null, severity, null); - setLocalizedMessage(messageText); - setTargetObject(targetObject); - } - - private String getLocalizedText() { - return _message; - } - - @Override - public String getText() { - return getLocalizedText(); - } - - @Override - public String getText(ClassLoader cl) { - return getLocalizedText(); - } - - @Override - public String getText(Locale l) { - return getLocalizedText(); - } - - @Override - public String getText(Locale l, ClassLoader cl) { - return getLocalizedText(); - } - - public void setLocalizedMessage(String message) { - _message = message; - } - } - - // for debugging - static final boolean DEBUG = Boolean.valueOf(Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jspvalidator")).booleanValue(); //$NON-NLS-1$ - - private static final String PLUGIN_ID_JSP_CORE = "org.eclipse.wst.jsdt.web.core"; //$NON-NLS-1$ - - /** - * Gets current validation project configuration based on current project - * (which is based on current document) - * - * @return ProjectConfiguration - */ - static private ProjectConfiguration getProjectConfiguration(IFile file) { - ProjectConfiguration projectConfiguration = null; - if (file != null) { - IProject project = file.getProject(); - if (project != null) { - try { - projectConfiguration = ConfigurationManager.getManager().getProjectConfiguration(project); - } catch (InvocationTargetException e) { - Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e); - } - } - } - - return projectConfiguration; - } - - /** - * Checks if validator is enabled according in Validation preferences - * - * @param vmd - * @return - */ - static boolean isBatchValidatorPreferenceEnabled(IFile file) { - if (file == null) { - return true; - } - - boolean enabled = true; - ProjectConfiguration configuration = JSPBatchValidator.getProjectConfiguration(file); - if (configuration != null) { - org.eclipse.wst.validation.internal.ValidatorMetaData metadata = ValidationRegistryReader.getReader().getValidatorMetaData(JSPBatchValidator.class.getName()); - if (configuration != null && metadata != null) { - if (!configuration.isBuildEnabled(metadata) && !configuration.isManualEnabled(metadata)) { - enabled = false; - } - } - } - return enabled; - } - - String fAdditionalContentTypesIDs[] = null; - - private IContentType[] fContentTypes = null; - - private IContentType fJSPFContentType = null; - - private JsValidator fJSPJavaValidator = new JsValidator(this); - - public void cleanup(IReporter reporter) { - - fJSPJavaValidator.cleanup(reporter); - } - - void doValidate(IValidationContext helper, IReporter reporter) throws ValidationException { - reporter.removeAllMessages(this); - - String[] uris = helper.getURIs(); - if (uris.length > 0) { - IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); - IFile currentFile = null; - for (int i = 0; i < uris.length && !reporter.isCancelled(); i++) { - currentFile = wsRoot.getFile(new Path(uris[i])); - if (currentFile != null && currentFile.exists()) { - if (shouldValidate(currentFile) && fragmentCheck(currentFile)) { - Message message = new LocalizedMessage(IMessage.LOW_SEVERITY, "" + (i + 1) + "/" + uris.length + " - " + currentFile.getFullPath().toString().substring(1)); - reporter.displaySubtask(this, message); - validateFile(currentFile, reporter); - } - if (JSPBatchValidator.DEBUG) { - System.out.println("validating: [" + uris[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - } else { - // if uris[] length 0 -> validate() gets called for each project - if (helper instanceof IWorkbenchContext) { - IProject project = ((IWorkbenchContext) helper).getProject(); - - Message message = new LocalizedMessage(IMessage.LOW_SEVERITY, NLS.bind(JSPCoreMessages.JSPBatchValidator_0, project.getFullPath())); - reporter.displaySubtask(this, message); - - JSPFileVisitor visitor = new JSPFileVisitor(reporter); - try { - // collect all jsp files for the project - project.accept(visitor, IResource.DEPTH_INFINITE); - } catch (CoreException e) { - if (JSPBatchValidator.DEBUG) { - e.printStackTrace(); - } - } - IFile[] files = visitor.getFiles(); - for (int i = 0; i < files.length && !reporter.isCancelled(); i++) { - if (shouldValidate(files[i]) && fragmentCheck(files[i])) { - - message = new LocalizedMessage(IMessage.LOW_SEVERITY, "" + (i + 1) + "/" + files.length + " - " + files[i].getFullPath().toString().substring(1)); - reporter.displaySubtask(this, message); - - validateFile(files[i], reporter); - } - if (JSPBatchValidator.DEBUG) { - System.out.println("validating: [" + files[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - } - } - - /** - * Checks if file is a jsp fragment or not. If so, check if the fragment - * should be validated or not. - * - * @param file - * Assumes shouldValidate was already called on file so it should - * not be null and does exist - * @return false if file is a fragment and it should not be validated, true - * otherwise - */ - private boolean fragmentCheck(IFile file) { - boolean shouldValidate = true; - // quick check to see if this is possibly a jsp fragment - if (getJSPFContentType().isAssociatedWith(file.getName())) { - // get preference for validate jsp fragments - boolean shouldValidateFragments = Boolean.valueOf(JSPFContentProperties.getProperty(JSPFContentProperties.VALIDATE_FRAGMENTS, file, true)).booleanValue(); - /* - * if jsp fragments should not be validated, check if file is really - * jsp fragment - */ - if (!shouldValidateFragments) { - boolean isFragment = isFragment(file); - shouldValidate = !isFragment; - } - } - return shouldValidate; - } - - /** - * Returns JSP fragment content type - * - * @return jspf content type - */ - private IContentType getJSPFContentType() { - if (fJSPFContentType == null) { - fJSPFContentType = Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT); - } - return fJSPFContentType; - } - - public ISchedulingRule getSchedulingRule(IValidationContext helper) { - if (helper instanceof IWorkbenchContext) { - /* - * Use a single build rule when running batch validation. - */ - return ResourcesPlugin.getWorkspace().getRuleFactory().buildRule(); - } - /* - * For other kinds of validation, use no specific rule - */ - return null; - } - - /** - * Gets list of content types this visitor is interested in - * - * @return All JSP-related content types - */ - private IContentType[] getValidContentTypes() { - if (fContentTypes == null) { - // currently "hard-coded" to be jsp & jspf - fContentTypes = new IContentType[] { Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSP), Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT) }; - if (fAdditionalContentTypesIDs != null) { - List allTypes = new ArrayList(Arrays.asList(fContentTypes)); - for (int i = 0; i < fAdditionalContentTypesIDs.length; i++) { - IContentType type = Platform.getContentTypeManager().getContentType(fAdditionalContentTypesIDs[i]); - if (type != null) { - allTypes.add(type); - } - } - fContentTypes = (IContentType[]) allTypes.toArray(new IContentType[allTypes.size()]); - } - } - return fContentTypes; - } - - /** - * Determines if file is jsp fragment or not (does a deep, indepth check, - * looking into contents of file) - * - * @param file - * assumes file is not null and exists - * @return true if file is jsp fragment, false otherwise - */ - private boolean isFragment(IFile file) { - boolean isFragment = false; - InputStream is = null; - try { - IContentDescription contentDescription = file.getContentDescription(); - // it can be null - if (contentDescription == null) { - is = file.getContents(); - contentDescription = Platform.getContentTypeManager().getDescriptionFor(is, file.getName(), new QualifiedName[] { IContentDescription.CHARSET }); - } - if (contentDescription != null) { - String fileCtId = contentDescription.getContentType().getId(); - isFragment = (fileCtId != null && ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT.equals(fileCtId)); - } - } catch (IOException e) { - // ignore, assume it's invalid JSP - } catch (CoreException e) { - // ignore, assume it's invalid JSP - } finally { - /* - * must close input stream in case others need it - * (IFile.getContents() requirement as well) - */ - if (is != null) { - try { - is.close(); - } catch (Exception e) { - // not sure how to recover at this point - } - } - } - return isFragment; - } - - /** - * Checks if fileName is some type of JSP (including JSP fragments) - * - * @param fileName - * @return true if filename indicates some type of JSP, false otherwise - */ - private boolean isJSPType(String fileName) { - boolean valid = false; - - IContentType[] types = getValidContentTypes(); - int i = 0; - while (i < types.length && !valid) { - valid = types[i].isAssociatedWith(fileName); - ++i; - } - return valid; - } - - private void performValidation(IFile f, IReporter reporter, IStructuredModel model) { - if (!reporter.isCancelled()) { - fJSPJavaValidator.performValidation(f, reporter, model); - } - - } - - /** - * @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement, - * java.lang.String, java.lang.Object) - */ - public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException { - fAdditionalContentTypesIDs = new String[0]; - if (data != null) { - if (data instanceof String && data.toString().length() > 0) { - fAdditionalContentTypesIDs = StringUtils.unpack(data.toString()); - } - } - } - - private boolean shouldValidate(IFile file) { - IResource resource = file; - do { - if (resource.isDerived() || resource.isTeamPrivateMember() || !resource.isAccessible() || resource.getName().charAt(0) == '.') { - return false; - } - resource = resource.getParent(); - } while ((resource.getType() & IResource.PROJECT) == 0); - return true; - } - - public void validate(IValidationContext helper, IReporter reporter) throws ValidationException { - doValidate(helper, reporter); - } - - /** - * Validate one file. It's assumed that the file has JSP content type. - * - * @param f - * @param reporter - */ - void validateFile(IFile f, IReporter reporter) { - IStructuredModel model = null; - try { - // get JSP model on behalf of all JSP validators - model = StructuredModelManager.getModelManager().getModelForRead(f); - if (!reporter.isCancelled() && model != null) { - reporter.removeAllMessages(this, f); - performValidation(f, reporter, model); - } - } catch (IOException e) { - Logger.logException(e); - } catch (CoreException e) { - Logger.logException(e); - } finally { - if (model != null) { - model.releaseFromRead(); - } - } - } - - public IStatus validateInJob(final IValidationContext helper, final IReporter reporter) throws ValidationException { - Job currentJob = Platform.getJobManager().currentJob(); - ISchedulingRule rule = null; - if (currentJob != null) { - rule = currentJob.getRule(); - } - IWorkspaceRunnable validationRunnable = new IWorkspaceRunnable() { - public void run(IProgressMonitor monitor) throws CoreException { - try { - doValidate(helper, reporter); - } catch (ValidationException e) { - throw new CoreException(new Status(IStatus.ERROR, JSPBatchValidator.PLUGIN_ID_JSP_CORE, 0, JSPBatchValidator.PLUGIN_ID_JSP_CORE, e)); - } - } - }; - try { - JavaCore.run(validationRunnable, rule, new NullProgressMonitor()); - } catch (CoreException e) { - if (e.getCause() instanceof ValidationException) { - throw (ValidationException) e.getCause(); - } - throw new ValidationException(new LocalizedMessage(IMessage.ERROR_AND_WARNING, e.getMessage()), e); - } - return Status.OK_STATUS; - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/validation/JSPValidator.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/validation/JSPValidator.java deleted file mode 100644 index baec3c0617..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/validation/JSPValidator.java +++ /dev/null @@ -1,405 +0,0 @@ -package org.eclipse.wst.jsdt.web.core.internal.validation; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceProxy; -import org.eclipse.core.resources.IResourceProxyVisitor; -import org.eclipse.core.resources.IWorkspaceRoot; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.jobs.ISchedulingRule; -import org.eclipse.wst.jsdt.web.core.internal.Logger; -import org.eclipse.wst.jsdt.web.core.internal.contentproperties.JSPFContentProperties; -import org.eclipse.wst.jsdt.web.core.internal.provisional.contenttype.ContentTypeIdForJSP; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList; -import org.eclipse.wst.validation.internal.core.Message; -import org.eclipse.wst.validation.internal.core.ValidationException; -import org.eclipse.wst.validation.internal.operations.IWorkbenchContext; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidationContext; -import org.eclipse.wst.validation.internal.provisional.core.IValidatorJob; -import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext; - -/** - * Performs some common JSP validation tasks - */ -public class JSPValidator implements IValidatorJob { - - protected class JSPFileVisitor implements IResourceProxyVisitor { - - private IContentType[] fContentTypes = null; - private List fFiles = new ArrayList(); - private IReporter fReporter = null; - - public JSPFileVisitor(IReporter reporter) { - fReporter = reporter; - } - - public final IFile[] getFiles() { - return (IFile[]) fFiles.toArray(new IFile[fFiles.size()]); - } - - /** - * Gets list of content types this visitor is interested in - * - * @return All JSP-related content types - */ - private IContentType[] getValidContentTypes() { - if (fContentTypes == null) { - // currently "hard-coded" to be jsp & jspf - fContentTypes = new IContentType[] { Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSP), Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT) }; - } - return fContentTypes; - } - - /** - * Checks if fileName is some type of JSP (including JSP fragments) - * - * @param fileName - * @return true if filename indicates some type of JSP, false otherwise - */ - private boolean isJSPType(String fileName) { - boolean valid = false; - - IContentType[] types = getValidContentTypes(); - int i = 0; - while (i < types.length && !valid) { - valid = types[i].isAssociatedWith(fileName); - ++i; - } - return valid; - } - - public boolean visit(IResourceProxy proxy) throws CoreException { - - // check validation - if (fReporter.isCancelled()) { - return false; - } - - if (proxy.getType() == IResource.FILE) { - - if (isJSPType(proxy.getName())) { - IFile file = (IFile) proxy.requestResource(); - if (file.exists()) { - - if (JSPValidator.DEBUG) { - System.out.println("(+) JSPValidator adding file: " + file.getName()); //$NON-NLS-1$ - } - fFiles.add(file); - - // don't search deeper for files - return false; - } - } - } - return true; - } - } - - protected class LocalizedMessage extends Message { - - private String _message = null; - - public LocalizedMessage(int severity, String messageText) { - this(severity, messageText, null); - } - - public LocalizedMessage(int severity, String messageText, IResource targetObject) { - this(severity, messageText, (Object) targetObject); - } - - public LocalizedMessage(int severity, String messageText, Object targetObject) { - super(null, severity, null); - setLocalizedMessage(messageText); - setTargetObject(targetObject); - } - - public String getLocalizedMessage() { - return _message; - } - - @Override - public String getText() { - return getLocalizedMessage(); - } - - @Override - public String getText(ClassLoader cl) { - return getLocalizedMessage(); - } - - @Override - public String getText(Locale l) { - return getLocalizedMessage(); - } - - @Override - public String getText(Locale l, ClassLoader cl) { - return getLocalizedMessage(); - } - - public void setLocalizedMessage(String message) { - _message = message; - } - } - - // for debugging - static final boolean DEBUG; - - private static final String PLUGIN_ID_JSP_CORE = "org.eclipse.wst.jsdt.web.core"; //$NON-NLS-1$ - - static { - String value = Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jspvalidator"); //$NON-NLS-1$ - DEBUG = value != null && value.equalsIgnoreCase("true"); //$NON-NLS-1$ - } - - private IContentType fJSPFContentType = null; - - public void cleanup(IReporter reporter) { - // nothing to do - } - - /** - * Checks if file is a jsp fragment or not. If so, check if the fragment - * should be validated or not. - * - * @param file - * Assumes shouldValidate was already called on file so it should - * not be null and does exist - * @return false if file is a fragment and it should not be validated, true - * otherwise - */ - private boolean fragmentCheck(IFile file) { - boolean shouldValidate = true; - // quick check to see if this is possibly a jsp fragment - if (getJSPFContentType().isAssociatedWith(file.getName())) { - // get preference for validate jsp fragments - boolean shouldValidateFragments = Boolean.valueOf(JSPFContentProperties.getProperty(JSPFContentProperties.VALIDATE_FRAGMENTS, file, true)).booleanValue(); - /* - * if jsp fragments should not be validated, check if file is really - * jsp fragment - */ - if (!shouldValidateFragments) { - boolean isFragment = isFragment(file); - shouldValidate = !isFragment; - } - } - return shouldValidate; - } - - protected String getAttributeValue(IStructuredDocumentRegion sdr, String attrName) { - ITextRegion r = getAttributeValueRegion(sdr, attrName); - if (r != null) { - return sdr.getText(r).trim(); - } - return ""; //$NON-NLS-1$ - } - - /** - * - * @param sdr - * @param attrName - * @return the ITextRegion for the attribute value of the given attribute - * name, case sensitive, null if no matching attribute is found - */ - protected ITextRegion getAttributeValueRegion(IStructuredDocumentRegion sdr, String attrName) { - ITextRegion valueRegion = null; - ITextRegionList subRegions = sdr.getRegions(); - for (int i = 0; i < subRegions.size(); i++) { - ITextRegion subRegion = subRegions.get(i); - if (subRegion.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME && sdr.getText(subRegion).equals(attrName)) { - for (int j = i; j < subRegions.size(); j++) { - subRegion = subRegions.get(j); - if (subRegion.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE) { - valueRegion = subRegion; - break; - } - } - break; - } - } - return valueRegion; - } - - /** - * - * @param sdr - * @return the jsp directive name - */ - protected String getDirectiveName(IStructuredDocumentRegion sdr) { - String name = ""; //$NON-NLS-1$ - ITextRegionList subRegions = sdr.getRegions(); - for (int j = 0; j < subRegions.size(); j++) { - ITextRegion subRegion = subRegions.get(j); - if (subRegion.getType() == "DOMJSPRegionContexts.JSP_DIRECTIVE_NAME") { - name = sdr.getText(subRegion); - break; - } - } - return name; - } - - /** - * Returns JSP fragment content type - * - * @return jspf content type - */ - private IContentType getJSPFContentType() { - if (fJSPFContentType == null) { - fJSPFContentType = Platform.getContentTypeManager().getContentType(ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT); - } - return fJSPFContentType; - } - - public ISchedulingRule getSchedulingRule(IValidationContext helper) { - return null; - } - - /** - * Determines if file is jsp fragment or not (does a deep, indepth check, - * looking into contents of file) - * - * @param file - * assumes file is not null and exists - * @return true if file is jsp fragment, false otherwise - */ - private boolean isFragment(IFile file) { - boolean isFragment = false; - InputStream is = null; - try { - IContentDescription contentDescription = file.getContentDescription(); - // it can be null - if (contentDescription == null) { - is = file.getContents(); - contentDescription = Platform.getContentTypeManager().getDescriptionFor(is, file.getName(), new QualifiedName[] { IContentDescription.CHARSET }); - } - if (contentDescription != null) { - String fileCtId = contentDescription.getContentType().getId(); - isFragment = (fileCtId != null && ContentTypeIdForJSP.ContentTypeID_JSPFRAGMENT.equals(fileCtId)); - } - } catch (IOException e) { - // ignore, assume it's invalid JSP - } catch (CoreException e) { - // ignore, assume it's invalid JSP - } finally { - // must close input stream in case others need it - if (is != null) { - try { - is.close(); - } catch (Exception e) { - // not sure how to recover at this point - } - } - } - return isFragment; - } - - private boolean shouldValidate(IFile file) { - IResource resource = file; - do { - if (resource.isDerived() || resource.isTeamPrivateMember() || !resource.isAccessible() || resource.getName().charAt(0) == '.') { - return false; - } - resource = resource.getParent(); - } while ((resource.getType() & IResource.PROJECT) == 0); - return true; - } - - public void validate(IValidationContext helper, IReporter reporter) throws ValidationException { - /* Added by BC ---- */ - - // if(true) return; - /* end Added by BC ---- */ - - String[] uris = helper.getURIs(); - IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot(); - if (uris.length > 0) { - IFile currentFile = null; - - for (int i = 0; i < uris.length && !reporter.isCancelled(); i++) { - currentFile = wsRoot.getFile(new Path(uris[i])); - if (currentFile != null && currentFile.exists()) { - if (shouldValidate(currentFile) && fragmentCheck(currentFile)) { - - int percent = (i * 100) / uris.length + 1; - Message message = new LocalizedMessage(IMessage.LOW_SEVERITY, percent + "% " + uris[i]); - reporter.displaySubtask(this, message); - - validateFile(currentFile, reporter); - } - if (JSPValidator.DEBUG) { - System.out.println("validating: [" + uris[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - } else { - - // if uris[] length 0 -> validate() gets called for each project - if (helper instanceof IWorkbenchContext) { - - IProject project = ((IWorkbenchContext) helper).getProject(); - JSPFileVisitor visitor = new JSPFileVisitor(reporter); - try { - // collect all jsp files for the project - project.accept(visitor, IResource.DEPTH_INFINITE); - } catch (CoreException e) { - if (JSPValidator.DEBUG) { - e.printStackTrace(); - } - } - IFile[] files = visitor.getFiles(); - for (int i = 0; i < files.length && !reporter.isCancelled(); i++) { - if (shouldValidate(files[i]) && fragmentCheck(files[i])) { - int percent = (i * 100) / files.length + 1; - Message message = new LocalizedMessage(IMessage.LOW_SEVERITY, percent + "% " + files[i].getFullPath().toString()); - reporter.displaySubtask(this, message); - - validateFile(files[i], reporter); - } - if (JSPValidator.DEBUG) { - System.out.println("validating: [" + files[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - } - } - - /** - * Validate one file. It's assumed that the file has JSP content type. - * - * @param f - * @param reporter - */ - protected void validateFile(IFile f, IReporter reporter) { - // subclasses should implement (for batch validation) - } - - public IStatus validateInJob(IValidationContext helper, IReporter reporter) throws ValidationException { - IStatus status = Status.OK_STATUS; - try { - validate(helper, reporter); - } catch (ValidationException e) { - Logger.logException(e); - status = new Status(IStatus.ERROR, JSPValidator.PLUGIN_ID_JSP_CORE, IStatus.ERROR, e.getLocalizedMessage(), e); - } - return status; - } -}
\ No newline at end of file diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/validation/JsValidator.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/validation/JsValidator.java deleted file mode 100644 index 2a345937ce..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/validation/JsValidator.java +++ /dev/null @@ -1,205 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2006, 2006 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * - *******************************************************************************/ -package org.eclipse.wst.jsdt.web.core.internal.validation; - -import java.io.IOException; -import java.util.List; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jface.text.IDocument; -import org.eclipse.wst.jsdt.core.compiler.IProblem; -import org.eclipse.wst.jsdt.web.core.internal.Logger; -import org.eclipse.wst.jsdt.web.core.internal.java.IJSPTranslation; -import org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslation; -import org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslationAdapter; -import org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslationAdapterFactory; -import org.eclipse.wst.jsdt.web.core.internal.java.JSPTranslationExtension; -import org.eclipse.wst.sse.core.StructuredModelManager; -import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion; -import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion; -import org.eclipse.wst.validation.internal.core.ValidationException; -import org.eclipse.wst.validation.internal.provisional.core.IMessage; -import org.eclipse.wst.validation.internal.provisional.core.IReporter; -import org.eclipse.wst.validation.internal.provisional.core.IValidationContext; -import org.eclipse.wst.validation.internal.provisional.core.IValidator; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument; -import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel; - -public class JsValidator extends JSPValidator { - private static final boolean DEBUG = Boolean.valueOf(Platform.getDebugOption("org.eclipse.wst.jsdt.web.core/debug/jspvalidator")).booleanValue(); //$NON-NLS-1$ - private IValidator fMessageOriginator; - - public JsValidator() { - this.fMessageOriginator = this; - } - - public JsValidator(IValidator validator) { - this.fMessageOriginator = validator; - } - - /** - * Assumed the message offset is an indirect position. In other words, an - * error from an included file. - * - * @param m - * @param translation - */ - private void adjustIndirectPosition(IMessage m, JSPTranslation translation) { - - if (!(translation instanceof JSPTranslationExtension)) { - return; - } - - IDocument jspDoc = ((JSPTranslationExtension) translation).getJspDocument(); - if (!(jspDoc instanceof IStructuredDocument)) { - return; - } - - IStructuredDocument sDoc = (IStructuredDocument) jspDoc; - IStructuredDocumentRegion[] regions = sDoc.getStructuredDocumentRegions(0, m.getOffset() + m.getLength()); - // iterate backwards until you hit the include directive - for (int i = regions.length - 1; i >= 0; i--) { - - IStructuredDocumentRegion region = regions[i]; - if (region.getType() == "script import region") { - if (getDirectiveName(region).equals("include")) { //$NON-NLS-1$ - ITextRegion fileValueRegion = getAttributeValueRegion(region, "file"); //$NON-NLS-1$ - m.setOffset(region.getStartOffset(fileValueRegion)); - m.setLength(fileValueRegion.getTextLength()); - break; - } - } - } - } - - /** - * Creates an IMessage from an IProblem - * - * @param problem - * @param f - * @param translation - * @param structuredDoc - * @return message representation of the problem, or null if it could not - * create one - */ - private IMessage createMessageFromProblem(IProblem problem, IFile f, JSPTranslation translation, IStructuredDocument structuredDoc) { - - int sourceStart = translation.getJspOffset(problem.getSourceStart()); - int sourceEnd = translation.getJspOffset(problem.getSourceEnd()); - if (sourceStart == -1) { - return null; - } - - // line number for marker starts @ 1 - // line number from document starts @ 0 - int lineNo = structuredDoc.getLineOfOffset(sourceStart) + 1; - - int sev = problem.isError() ? IMessage.HIGH_SEVERITY : IMessage.NORMAL_SEVERITY; - - IMessage m = new LocalizedMessage(sev, problem.getMessage(), f); - - m.setLineNo(lineNo); - m.setOffset(sourceStart); - m.setLength(sourceEnd - sourceStart + 1); - - // need additional adjustment for problems from - // indirect (included) files - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=119633 - if (translation.isIndirect(problem.getSourceStart())) { - adjustIndirectPosition(m, translation); - } - - return m; - } - - void performValidation(IFile f, IReporter reporter, IStructuredModel model) { - - if (model instanceof IDOMModel) { - IDOMModel domModel = (IDOMModel) model; - setupAdapterFactory(domModel); - - IDOMDocument xmlDoc = domModel.getDocument(); - JSPTranslationAdapter translationAdapter = (JSPTranslationAdapter) xmlDoc.getAdapterFor(IJSPTranslation.class); - JSPTranslation translation = translationAdapter.getJSPTranslation(); - - if (!reporter.isCancelled()) { - translation.setProblemCollectingActive(true); - translation.reconcileCompilationUnit(); - List problems = translation.getProblems(); - // add new messages - for (int i = 0; i < problems.size() && !reporter.isCancelled(); i++) { - IMessage m = createMessageFromProblem((IProblem) problems.get(i), f, translation, domModel.getStructuredDocument()); - if (m != null) { - reporter.addMessage(fMessageOriginator, m); - } - } - } - } - } - - /** - * When loading model from a file, you need to explicitly add adapter - * factory. - * - * @param sm - */ - private void setupAdapterFactory(IStructuredModel sm) { - if (sm.getFactoryRegistry().getFactoryFor(IJSPTranslation.class) == null) { - JSPTranslationAdapterFactory factory = new JSPTranslationAdapterFactory(); - sm.getFactoryRegistry().addFactory(factory); - } - } - - @Override - public void validate(IValidationContext helper, IReporter reporter) throws ValidationException { - reporter.removeAllMessages(this); - super.validate(helper, reporter); - } - - /** - * Validate one file. It's assumed that the file has JSP content type. - * - * @param f - * @param reporter - */ - @Override - protected void validateFile(IFile f, IReporter reporter) { - if (JsValidator.DEBUG) { - Logger.log(Logger.INFO, getClass().getName() + " validating: " + f); //$NON-NLS-1$ - } - - IStructuredModel model = null; - try { - // get jsp model, get tranlsation - model = StructuredModelManager.getModelManager().getModelForRead(f); - if (!reporter.isCancelled() && model != null) { - // get jsp model, get translation - if (model instanceof IDOMModel) { - reporter.removeAllMessages(fMessageOriginator, f); - performValidation(f, reporter, model); - } - } - } catch (IOException e) { - Logger.logException(e); - } catch (CoreException e) { - Logger.logException(e); - } finally { - if (model != null) { - model.releaseFromRead(); - } - } - } -} diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/text/IJSPPartitions.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/text/IJSPPartitions.java deleted file mode 100644 index 52bef9856c..0000000000 --- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/text/IJSPPartitions.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.eclipse.wst.jsdt.web.core.text; - -import org.eclipse.wst.html.core.text.IHTMLPartitions; - -/** - * This interface is not intended to be implemented. It defines the partition - * types for JSP. Clients should reference the partition type Strings defined - * here directly. - * - * @since 1.1 - */ -public interface IJSPPartitions { - - // String JSP_COMMENT = "org.eclipse.wst.jsdt.web.JSP_COMMENT"; - // //$NON-NLS-1$ - String JSP_COMMENT = IHTMLPartitions.SCRIPT; - String JSP_CONTENT_DELIMITER = IJSPPartitions.JSP_SCRIPT_PREFIX + "DELIMITER"; //$NON-NLS-1$ - // String JSP_CONTENT_JAVA = JSP_SCRIPT_PREFIX + "JAVA"; //$NON-NLS-1$ - String JSP_CONTENT_JAVA = IHTMLPartitions.SCRIPT; - // String JSP_CONTENT_JAVASCRIPT = JSP_SCRIPT_PREFIX + "JAVASCRIPT"; - // //$NON-NLS-1$ - String JSP_CONTENT_JAVASCRIPT = IHTMLPartitions.SCRIPT; - - // String JSP_DEFAULT = "org.eclipse.wst.jsdt.web.DEFAULT_JSP"; - // //$NON-NLS-1$ - String JSP_DEFAULT = IHTMLPartitions.SCRIPT; - - String JSP_DEFAULT_EL = IJSPPartitions.JSP_SCRIPT_PREFIX + "JSP_EL"; //$NON-NLS-1$; - String JSP_DEFAULT_EL2 = IJSPPartitions.JSP_SCRIPT_PREFIX + "JSP_EL2"; //$NON-NLS-1$ - String JSP_DIRECTIVE = "org.eclipse.wst.jsdt.web.JSP_DIRECTIVE"; //$NON-NLS-1$ - - String JSP_SCRIPT_PREFIX = "org.eclipse.wst.jsdt.web.SCRIPT."; //$NON-NLS-1$ -} |